Skip to main content
 首页 » 编程设计

python之排序 os.listdir 文件 Python

2025年05月04日12mengfanrong

如果下载了几年的数据,这些数据存储在具有以下命名约定的文件中,year_day.dat。比如2014_1.dat这个文件里面有2014年1月1日的数据,我需要读取这些按天排序的数据文件,2014_1.dat,2014_2.dat,2014_3.dat直到年底。在文件夹中,它们按顺序列出但是当我在目录中创建文件列表时,它们被重新排序 2014_1.dat、2014_10.dat、2014_100.dat、2014_101.dat...2014.199.dat、2014_2.dat。 我想我需要使用排序功能,但如何强制它按天对列出的文件进行排序,以便我可以继续处理它们? 到目前为止,这是代码:

import sys, os, gzip, fileinput, collections 
# Set the input/output directories 
wrkDir = "C:/LJBTemp" 
inDir = wrkDir + "/Input" 
outDir = wrkDir + "/Output" 
# here we go 
inList = os.listdir(inDir)  # List all the files in the 'Input' directory 
print inList  #print to screen reveals 2014_1.dat.gz followed by 2014_10.dat.gz NOT    2014_2.dat.gz HELP 
d = {} 
for fileName in inList:     # Step through each input file  
    readFileName = inDir + "/" + fileName 
 
    with gzip.open(readFileName, 'r') as f: #call built in utility to unzip file for reading 
      for line in f: 
          city, long, lat, elev, temp = line.split() #create dictionary 
          d.setdefault(city, []).append(temp) #populate dictionary with city and associated temp data from each input file 
          collections.OrderedDict(sorted(d.items(), key=lambda d: d[0])) # QUESTION? why doesn't this work 
          #now collect and write to output file 
outFileName = outDir + "/" + "1981_maxT.dat" #create output file in output directory with .dat extension 
with open(outFileName, 'w') as f: 
     for city, values in d.items(): 
        f.write('{} {}\n'.format(city, ' '.join(values))) 
 
print "All done!!" 
raw_input("Press <enter>") # this keeps the window open until you press "enter" 

请您参考如下方法:

如果你不介意使用第三方库,你可以使用 natsort库,正是为这种情况而设计的。

import natsort 
inList = natsort.natsorted(os.listdir(inDir)) 

这应该会处理所有数字排序,而不必担心细节。

您还可以使用 ns.PATH 选项使排序算法具有路径感知能力:

from natsort import natsorted, ns 
inList = natsorted(os.listdir(inDir), alg=ns.PATH) 

完全公开,我是 natsort 的作者。