2011-07-20 52 views
8

我發現這個目錄檢查網頁上的代碼並修改了一下,所以它會打印出添加的文件。有一個浮標每隔一段時間發送一次讀數,但有時連接丟失,而不是一個文件發送多個文件。我需要程序根據創建日期爲我排序。有沒有辦法做到這一點?按日期排序文件

import os, time 
path_to_watch = 'c://Users//seplema//Documents//arvuti' 
before = dict([(f, None) for f in os.listdir (path_to_watch)]) 
while 1: 
    after = dict([(f, None) for f in os.listdir (path_to_watch)]) 
    added = [f for f in after if not f in before] 
    if before == after: 
     1==1 
    else: 
     if len(added)==1: 
      print added[0] 
     else: 
      for i in range (0,len(added)): 
       print added[i] 
    time.sleep(10) 
    before = after 
+2

http://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python – Jacob

回答

23
added.sort(key=lambda x: os.stat(os.path.join(path_to_watch, x)).st_mtime) 

將由文件

使用st_ctimest_mtime爲Windows創建時間instaed的最後修改時間排序added列表(這並不意味着在其他平臺上)。

+1

'os.path.join' is cross平臺 - 你不必知道適當的分隔符是什麼。 – agf

+2

或簡單地'added.sort(key = os.path.getmtime)' – Sheljohn