如果已下载数年的数据,这些数据存储在具有以下命名约定的文件中: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 https://github.com/SethMMorton/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
author.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)