1

I want to fetch all the local disks and their partitions then as a result return all the data like "total space, used space and free space". The problem is to check if the partition is exist then continue to end if not through error.

In the code below, my local disk has three partitions: C:\, D:\, F:\ . However, partition G:\ is not exist so it is hang then closed.

I am using Python 3.6 and Pycharm community.

def disk_usage(self):
        disks = ['C','D','F','G']
        for i in disks:
            total, used, free = shutil.disk_usage(i+":\\")
            try:
                print("Drive " + i + " as follows:")
                print("==================")
                print("Total: %d GB" % (total // (2**30)))
                print("Used: %d GB" % (used // (2**30)))
                print("Free: %d GB" % (free // (2**30)))
                print("===========")
                print("")
            except GetoptError as err:
               print(err)

Thanks in advance,

1 Answer 1

2

you could see if the path exists before computing size:

p = i+":"+os.sep
if os.path.exists(p):
    total, used, free = shutil.disk_usage(p)

or catch the OSError exception

try:
   total, used, free = shutil.disk_usage(i+":\\")
   ...
catch OSError:
    pass

As an aside, it would be a good idea to obtain that drives list dynamically too (see Is there a way to list all the available drive letters in python?).

That probably still requires to check for existence / catch exception (disk not in drive of such) as explained above.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.