Sort os.listdir files Python



如果下载了几年的数据存储在具有以下命名约定的文件中,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作者。

如果您的所有文件都以"2014_"开头,请尝试此操作:

sorted(inList, key = lambda k: int(k.split('_')[1].split('.')[0]))

否则,利用元组比较,先按年份排序,然后按文件名的第二部分排序。

sorted(inList, key = lambda k: (int(k.split('_')[0]), int(k.split('_')[1].split('.')[0])))

>dict.items返回(key, item)对的列表。

关键函数仅使用第一个元素(d[0] => key => 城市)。

还有另一个问题:sorted返回已排序列表的新副本,并且不会就地对列表进行排序。此外,OrderedDict对象是创建的,而不是分配给任何地方;实际上,您不需要在每次将项目追加到列表时进行排序。

删除... sorted ...行,并替换以下行:

with open(outFileName, 'w') as f:
     for city, values in d.items():
        f.write('{} {}n'.format(city, ' '.join(values)))

以下将解决您的问题:

with open(outFileName, 'w') as f:
     for city, values in d.items():
        values.sort(key=lambda fn: map(int, os.path.splitext(fn)[0].split('_')))
        f.write('{} {}n'.format(city, ' '.join(values)))

顺便说一句,与其手动加入硬编码分隔符/,不如使用 os.path.join

inDir + "/" + fileName
 =>
os.path.join(inDir, fileName)

最新更新