【问题标题】:Python file path and sizePython文件路径和大小
【发布时间】:2013-06-06 04:42:17
【问题描述】:

我一直在尝试列出一个目录中的所有文件及其子目录、它的路径和它在 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 中为文件路径和大小创建数据结构,因为我还需要进行一些排序。 谢谢你:)

【问题讨论】:

    标签: python linux file path size


    【解决方案1】:
    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")
    

    【讨论】:

    • path/to/dir 用于追加路径?
    猜你喜欢
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多