如果您下载了多年的数据并以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"