簡體   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