Hsin Hsin - 14 days ago 9
Python Question

OS.STAT().ST_SIZE gives me incorrect size in Python

os.stat doesn't give me correct output I only get 8192 byte for every file. Code below

import os

path = "C:\\"

filelist = os.listdir(path)

for i in filelist:
if os.path.isdir(os.path.join(path, i)):
print os.path.join(path, i), "is DIR"
else:
# fs = filesize
fs = os.stat(path).st_size
# fs = os.path.getsize(path)

print os.path.join(path, i), "size is", fs


Here is output:

C:\$Recycle.Bin is DIR
C:\Config.Msi is DIR
C:\Documents and Settings is DIR
C:\hiberfil.sys size is 8192
C:\pagefile.sys size is 8192
C:\PerfLogs is DIR
C:\Program Files is DIR
C:\Program Files (x86) is DIR
C:\ProgramData is DIR
C:\Python27 is DIR
C:\Recovery is DIR
C:\shared.log size is 8192
C:\System Volume Information is DIR
C:\Users is DIR
C:\vcredist_x86.log size is 8192
C:\Windows is DIR


Why the biggest number is 8192? All files that are not dir have much bigger size than that. Output is the same for os.stat(path).st_size and os.path.getsize(path). Thanks in advance.

Answer

You forgot to os.path.join(path, i) when checking the file size with os.stat(), so you always get the size for C:\ (which is 8192, windows specific stuff). Fixed script:

import os

path = "C:\\"

filelist = os.listdir(path)

for i in filelist:
    filepath = os.path.join(path, i)
    if os.path.isdir(filepath):
        print filepath, "is DIR"
    else:
        # fs = filesize
        fs = os.stat(filepath).st_size

        print filepath, "size is", fs