def size_of_dir(dirname):
print("Size of directory: ")
print(os.path.getsize(dirname))
is the code in question. dirname is a directory with 130 files of about 1kb each. When I call this function, it returns 4624, which is NOT the size of the directory...why is this?
path. getsize() method in Python is used to check the size of specified path. It returns the size of specified path in bytes. The method raise OSError if the file does not exist or is somehow inaccessible.
The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats.
exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not.
Using os.path.getsize()
will only get you the size of the directory, NOT of its content. So if you call getsize()
on any directory you will always get the same size since they are all represented the same way. On contrary, if you call it on a file, it will return the actual file size.
If you want the content you will need to do it recursively, like below:
sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With