按日期排序文件
我在网上找到了一段检查文件夹的代码,并稍微修改了一下,让它可以打印出新增的文件。我有一个浮标,它会不时发送一些数据给我,但有时候连接会断掉,这样它就会一次发送多个文件。我需要这个程序能帮我按创建日期来整理这些文件。有没有办法做到这一点?
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
1 个回答
27
added.sort(key=lambda x: os.stat(os.path.join(path_to_watch, x)).st_mtime)
这段代码会根据文件的最后修改时间来对 added
列表进行排序。
在Windows系统上,使用 st_ctime
来获取文件的创建时间(在其他系统上可能不一样)。