我在编写一个程序,它需要一个命令行参数,扫描参数提供的目录树并创建目录中每个文件的列表,然后对其进行排序通过文件的长度。从目录参数中获取文件,按大小排序
我没有太大的脚本家伙 - 但这是我有什么,它不工作:
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"
任何人都可以点我在正确的方向?
我建议阅读功能['帮助Ø s.walk'](http://docs.python.org/2/library/os.html#os.walk)。这似乎是处理目录树的正确选择。如果你看看这个函数的例子,你会看到,你正在一个很好的方式... – koffein
我认为你最后一行之前是没有必要的。实际上这行是导致错误... – koffein
@koffein我已经更新了我的代码,但它仍然给我一个错误。 –