2011-07-20 60 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