Reputation: 415
I am developing on OSX and My book states:
Calling
os.path.getsize(path)
will return the size in bytes of the file in the path argument. Example:
os.path.getsize('C:\\Windows\\System32\\calc.exe'`)
> 776192
It states that os.path.getsize()
gives is the size in bytes but when I try to find the size of a folder on my desktop, it gives weird results.
There's a file on my desktop namely Music. I wrote this code in the shell:
os.path.getsize('/Users/apple/Desktop/Music')
> 510
This means that Music
's size must be 510 bytes but it has a size of 1.32GB!
Upvotes: 1
Views: 3613
Reputation: 91535
This is because you're asking for the size of the directory itself, not the size of its contents. A directory in Unix (OSX) is considered to be a special file that contains meta data; Information that describes the directory on the file system. what .getsize()
is telling you is that the meta data only occupies 510 bytes.
Notice the first example your book gives is asking for the size of a file called calc.exe
, not a directory.
To get the total size of the contents of a directory, you need to recursively walk the entire hierarchy and call getsize()
on every file. Here is a one line solution to do this:
sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])
Where '.'
is the base path for the directory you're trying to get the size of.
Upvotes: 1
Reputation: 799
You are asking for the size allocated by the directory only. Not the contents within it. os.path.getsize()
can get you the size of a file.
Note: A folder is actually considered to be "empty" if it contains subfolders only and no files.
Upvotes: 0