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


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

是有问题的代码。 dirname 是一个包含 130 个文件的目录,每个文件约 1kb。当我调用这个函数时,它返回 4624这不是目录的大小......这是为什么呢?

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

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

len(os.listdir(dirname))

要获得数据总量,您可以使用此问题中的代码,即(如@linker发布)

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

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

如果你想要内容,你需要递归地做,如下所示:

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

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

>>> 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)
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"

最新更新