gpt4 book ai didi

Python文件路径和大小

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:02 25 4
gpt4 key购买 nike

我一直在尝试在 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 中为文件路径和大小创建数据结构,因为我还需要进行一些排序。谢谢:)

最佳答案

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

对于数据结构,您可以使用(路径,大小)元组列表:

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

关于Python文件路径和大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16953807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com