gpt4 book ai didi

python - 如何在获取所有文件大小的同一函数中获取总目录大小? (Python)

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

我正在使用以下函数从目标目录向下获取系统中的所有文件大小。

def get_files(target):
# Get file size and modified time for all files from the target directory and down.
# Initialize files list
filelist = []
# Walk the directory structure
for root, dirs, files in os.walk(target):
# Do not walk into directories that are mount points
dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs)
for name in files:
# Construct absolute path for files
filename = os.path.join(root, name)
# Test the path to account for broken symlinks
if os.path.exists(filename):
# File size information in bytes
size = float(os.path.getsize(filename))
# Get the modified time of the file
mtime = os.path.getmtime(filename)
# Create a tuple of filename, size, and modified time
construct = filename, size, str(datetime.datetime.fromtimestamp(mtime))
# Add the tuple to the master filelist
filelist.append(construct)
return(filelist)

如何修改它以包括包含目录和目录总大小的第二个列表?我正在尝试将此操作包含在一个函数中,希望比在单独的函数中执行第二次遍历以获取目录信息和大小更有效。

我们的想法是能够使用前 20 个最大文件的排序列表和前 10 个最大目录的第二个排序列表进行报告。

感谢你们的任何建议。

最佳答案

我在字典中而不是列表中输出目录,但看看你是否喜欢它:

def get_files(target):
# Get file size and modified time for all files from the target directory and down.
# Initialize files list
filelist = []
dirdict = {}
# Walk the directory structure
for root, dirs, files in os.walk(target):
# Do not walk into directories that are mount points
dirs[:] = filter(lambda dir: not os.path.ismount(os.path.join(root, dir)), dirs)
for name in files:
# Construct absolute path for files
filename = os.path.join(root, name)
# Test the path to account for broken symlinks
if os.path.exists(filename):
# File size information in bytes
size = float(os.path.getsize(filename))
# Get the modified time of the file
mtime = os.path.getmtime(filename)
# Create a tuple of filename, size, and modified time
construct = filename, size, str(datetime.datetime.fromtimestamp(mtime))
# Add the tuple to the master filelist
filelist.append(construct)
if root in dirdict.keys():
dirdict[root] += size
else:
dirdict[root] = size
return(filelist, dirdict)

如果您希望将指令作为元组列表,只需执行以下操作:

dirdict.items()

关于python - 如何在获取所有文件大小的同一函数中获取总目录大小? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560085/

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