繁体   English   中英

排序os.listdir文件Python

[英]Sort os.listdir files Python

如果已经按照以下命名约定(year_day.dat)下载了存储在文件中的数年数据。 例如,名为2014_1.dat的文件具有2014年1月1日的数据。我需要读取按日期2014_1.dat,2014_2.dat,2014_3.dat排序的数据文件,直到年底。 在文件夹中,当我在目录中创建文件列表时,它们以有序BUT列出。它们被重新排序为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返回已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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM