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

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

4

4 回答 4

14

此值 (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)]).
于 2012-05-01T21:28:52.040 回答
7

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

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

sum([os.path.getsize(f) for f in os.listdir('.') if os.path.isfile(f)])
于 2012-05-01T21:25:42.060 回答
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)
于 2021-03-22T14:13:47.283 回答
-2
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”

于 2020-04-11T09:25:58.253 回答