I'm trying to compute a folder's size in Python, but I have strange result.
This is a snippet of my code:
def bestsize(filepath):
""" Return a tuple with 3 values. The first is the file (or folder size). The second and third
have sense only for folder and are the number of files and subdirectories in folder
"""
from os.path import getsize, isdir
if not(isdir(filepath)): return (getsize(filepath), 1, 0)
else:
lf = []
ld = []
for root, dirs, files in os.walk(filepath):
for name in files: lf.append(os.path.join(root, name))
for dir in dirs: ld.append(os.path.join(root, dir))
return (sum(getsize(i) for i in lf), len(lf), len(ld))
I have made some tests on it comparing result as said by Windows's Explorer.
I have created a folder named "temp", and in it is a subfolder called temp and a file of 7 bytes called ciao.txt
. The temp folder is empty.
If I execute my function I obtain that my main folder is 7 bytes in size. But with Windows Explorer I obtain 4096 bytes.
Must I compute a default size for all, also empty, subfolders?
The default function getsize
in the os module returns 0 for all directories.
Edit: I have tested my code on a NTFS file system partition
Edit: Thanks, now I have understood. What I would like to do is a better dir/ls command. I use the former sum computed using getsize, now that I have understood the difference it is fine for me.
Edit2: I have edited the code putting my last version.
.
and..
entries. While the filesystem could create these lazily, that's not what HFS+, ext3, etc. do.) – abarnert Jul 11 '13 at 21:32