OS.STAT()。ST_SIZE在Python中给出了不正确的大小

时间:2016-11-24 09:52:57

标签: python python-2.7

os.stat没有给我正确的输出我每个文件只得到8192字节。代码

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

这是输出:

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

为什么最大的数字是8192?所有非dir的文件都有比这更大的文件。 os.stat(path).st_size和os.path.getsize(path)的输出相同。提前谢谢。

1 个答案:

答案 0 :(得分:2)

在使用os.path.join(path, i)检查文件大小时忘记了os.stat(),因此您始终可以获得C:\的大小(即8192,特定于Windows的内容)。固定脚本:

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