Obtaining Python Directory Capacity

Asked 2 years ago, Updated 2 years ago, 91 views

Is there a way to get the capacity of the directory in Python?
I thought that using os.path.getsize() as you would get the file size would give you the capacity of the directory, but it all comes out as zero. Can anyone write a code to get the full capacity of the directory?

Windows 10 and Python 3.8 are in use.

Thank you!

python3 operating-system size

2022-09-20 19:13

1 Answers

Note/code link

import os
print(os.path.getsize("example.jpg"))

You can obtain the capacity of the file with the above code

import os
def get_dir_size(path='.'):
    total = 0
    with os.scandir(path) as it:
        for entry in it:
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += get_dir_size(entry.path)
    return total

You can also get it this way as get_dir_size

#Example
import os
def get_dir_size(path='.'):
    total = 0
    with os.scandir(path) as it:
        for entry in it:
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += get_dir_size(entry.path)
    return total

dir = input ("Enter directory path")
print(get_dir_size(path=dir))


2022-09-20 19:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.