gpt4 book ai didi

python - 从目录参数中获取文件,按大小排序

转载 作者:太空狗 更新时间:2023-10-29 18:20:27 39 4
gpt4 key购买 nike

我正在尝试编写一个程序,它接受命令行参数,扫描参数提供的目录树并创建目录中每个文件的列表,然后按文件长度排序。

我不是一个脚本专家 - 但这是我所拥有的,但它不起作用:

import sys
import os
from os.path import getsize

file_list = []

#Get dirpath
dirpath = os.path.abspath(sys.argv[0])
if os.path.isdir(dirpath):
#Get all entries in the directory
for root, dirs, files in os.walk(dirpath):
for name in files:
file_list.append(name)
file_list = sorted(file_list, key=getsize)
for item in file_list:
sys.stdout.write(str(file) + '\n')

else:
print "not found"

谁能指出我正确的方向?

最佳答案

这是一种使用生成器的方法。对于大量文件应该更快......

这是两个例子的开头:

import os, operator, sys
dirpath = os.path.abspath(sys.argv[0])
# make a generator for all file paths within dirpath
all_files = ( os.path.join(basedir, filename) for basedir, dirs, files in os.walk(dirpath) for filename in files )

如果你只想要一个没有大小的文件列表,你可以使用这个:

sorted_files = sorted(all_files, key = os.path.getsize)

但是如果你想要列表中的文件和路径,你可以使用这个:

# make a generator for tuples of file path and size: ('/Path/to/the.file', 1024)
files_and_sizes = ( (path, os.path.getsize(path)) for path in all_files )
sorted_files_with_size = sorted( files_and_sizes, key = operator.itemgetter(1) )

关于python - 从目录参数中获取文件,按大小排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252669/

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