0

我一直在尝试列出目录中的所有文件及其子目录、它的路径和它在 python 中的大小。不知何故,仅显示其目录中的文件,而不显示子目录中的文件。

import os
from os.path import join, getsize,abspath, isfile

fo=open("Size Listing.txt","a")


def size_list(mypath):
f = []
for (dirpath, dirname, filenames) in os.walk(mypath):
    f.extend(filenames)

for i in f:
    fo.write("\nPath: ")
    fo.write(abspath(i))
    fo.write(" Size: ")
    fo.write(str(getsize(join(mypath,i))))
    fo.write(" bytes")


fo.close()

有人可以帮我吗?任何人都可以建议如何在 Python 中为文件路径和大小创建数据结构,因为我还需要进行一些排序。谢谢 :)

4

1 回答 1

0
import os
from os.path import join, getsize

def size_list(mypath):
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                fo.write("\nPath: " +  os.path.join(root, f))
                fo.write("\tSize: " +  str(getsize(os.path.join(root, f))) + " bytes")

size_list("path/to/dir")

对于数据结构,您可以使用 (Path, size) 的元组列表:

def size_list(mypath):
    my_list = []
    with open("PathTest.txt","w") as of:
        for root, dirs, files in os.walk(mypath):
            for f in files:
                my_file = os.path.join(root, f)
                file_size = getsize(my_file)
                my_list.append((my_file, file_size))
                fo.write("\nPath: " +  my_file)
                fo.write("\tSize: " +  str(file_size) + " bytes")
于 2013-06-06T05:17:00.157 回答