Skip to main content
 首页 » 编程设计

python之通过 python 按大小排序文件列表

2025年05月04日11zhengyun_ustc

目录列表中的示例转储:

hello:3.1 GB 
world:1.2 MB 
foo:956.2 KB 

以上列表的格式为FILE:VALUE UNIT。如何根据文件大小对上面的每一行进行排序?

我想也许可以通过模式“:VALUE UNIT”(或以某种方式使用定界符)为单元解析每一行,然后通过 ConvertAll engine 运行它,以字节为单位接收每个值的大小,将其与行的其余部分(文件名)进行哈希处理,然后通过大小对生成的字典对进行排序。

问题是,我对模式匹配一​​无所知。但我看到你可以对 dictionary 进行排序

如果有更好的方向来解决这个问题,请告诉我。


编辑:

我的列表实际上在一个文件中。从(很棒的)Alex Martelli 的答案中汲取灵感,我编写了以下代码,从一个文件中提取、排序并写入另一个文件。

#!/usr/bin/env python 
 
sourceFile = open("SOURCE_FILE_HERE", "r") 
allLines = sourceFile.readlines() 
sourceFile.close() 
 
print "Reading the entire file into a list." 
 
cleanLines = [] 
 
for line in allLines: 
    cleanLines.append(line.rstrip()) 
 
mult = dict(KB=2**10, MB=2**20, GB=2**30) 
 
def getsize(aline): 
  fn, size = aline.split(':', 1) 
  value, unit = size.split(' ') 
  multiplier = mult[unit] 
  return float(value) * multiplier 
 
print "Writing sorted list to file." 
 
cleanLines.sort(key=getsize) 
 
writeLines = open("WRITE_OUT_FILE_HERE",'a') 
 
for line in cleanLines: 
    writeLines.write(line+"\n") 
 
writeLines.close() 

请您参考如下方法:

thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB'] 
 
mult = dict(KB=2**10, MB=2**20, GB=2**30) 
 
def getsize(aline): 
  fn, size = aline.split(':', 1) 
  value, unit = size.split(' ') 
  multiplier = mult[unit] 
  return float(value) * multiplier 
 
thelines.sort(key=getsize) 
print thelines 

根据需要发出 ['foo:956.2 KB', 'world:1.2 MB', 'hello:3.1 GB']。当然,如果 KB、MB 和 GB 没有耗尽您感兴趣的单位集,您可能必须向 mult 添加一些条目。