我正在编写一个脚本来列出目标目录中最大的 20 个文件。获得文件后,我会对大小进行一些数学运算,以应用正确的人类可读的大小信息,即 Kb、Mb、Gb。
然而,这使排序变得混乱。我怎样才能做到这一点,并保持排序顺序不变?
#! /usr/bin/env python
import operator, os, sys
args = sys.argv
if len(args) != 2:
print "You must one enter one directory as an argument."
sys.exit(1)
else:
target = args[1]
data = {}
for root, dirs, files in os.walk(target):
for name in files:
filename = os.path.join(root, name)
if os.path.exists(filename):
size = float(os.path.getsize(filename))
data[filename] = size
sorted_data = sorted(data.iteritems(), key=operator.itemgetter(1), reverse=True)
total = str(len(sorted_data))
while len(sorted_data) > 20:
sorted_data.pop()
final_data = {}
for name in sorted_data:
size = str(name[1])
if size >= 1024:
size = round(float(size) / 1024, 2)
if size >= 1024:
size = round(size / 1024, 2)
if size >= 1024:
size = round(size / 1024, 2)
size = str(size) + "Gb"
else:
size = str(size) + "Mb"
else:
size = str(size) + "Kb"
final_data[name] = size
print "The 20 largest files are:\n"
for name in final_data:
print str(final_data[name]) + " " + str(name)
print "\nThere are a total of " + total + " files located in " + target