os.path.getsize返回不正确的值?

时间:2012-05-01 21:20:59

标签: python file directory size

def size_of_dir(dirname):
    print("Size of directory: ")
    print(os.path.getsize(dirname))

是有问题的代码。 dirname是一个目录,其中 130 文件各约为 1kb 。当我调用此函数时,它会返回 4624 ,这是 NOT 目录的大小......为什么会这样?

4 个答案:

答案 0 :(得分:10)

此值(4624B)表示描述该目录的文件的大小。目录被描述为inode(http://en.wikipedia.org/wiki/Inode),其中包含有关其包含的文件和目录的信息。

要获取该路径中的文件/子目录数,请使用:

len(os.path.listdir(dirname))

要获取数据总量,您可以使用代码in this question,即(如@linker发布的)

 sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)]).

答案 1 :(得分:5)

使用os.path.getsize()只会获得目录的大小,的内容。因此,如果您在任何目录上调用getsize(),您将始终获得相同的大小,因为它们都以相同的方式表示。相反,如果您在文件上调用它,它将返回实际文件大小。

如果您需要内容,则需要递归执行,如下所示:

sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])

答案 2 :(得分:2)

第一个答案给我带来了这个:

>>> sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])
1708

这对我来说也不正确:((我确实检查了我的 cwd)

下面的代码给我带来了更接近的结果

total_size = 0
for folders, subfolders, files in os.walk(dirname):
    for file in files:
        total_size += os.path.getsize(os.path.join(folders, file))
print(total_size)

答案 3 :(得分:-1)

import os

def create_python_script(filename):
    comments = "# Start of a new Python Program"
    #filesize = 0
    with open(filename, 'w') as new_file:
        new_file.write(comments)
        cwd=os.getcwd()
        fpath = os.path.abspath(filename)
        filesize=os.path.getsize(fpath)
    return(filesize)

print(create_python_script('newprogram.py'))

应该为31个字节,但结果为“ 0”

相关问题