Second newest file

半腔热情 提交于 2019-12-11 11:17:11

问题


I need the second newest file.

In this thread the newest is found:

Python get most recent file in a directory with certain extension

which uses this construct:

newest = min(glob.iglob('upload/*.log'), key=os.path.getctime)

However, how can I get not the min or max but the second element?


回答1:


I think this can be a suitable solution:

# for the min + 1
sorted(glob.iglob('*.log'), key=os.path.getctime)[1]

# for the newest
sorted(glob.iglob('*.log'), key=os.path.getctime)[-1]

# for the second newest ( max - 1)
sorted(glob.iglob('*.log'), key=os.path.getctime)[-2]

So basically glob.iglob('*.log') is just an array (to be more precise it result is a generator) - you can sort it by ctime and find what you want.




回答2:


sorted_list = sorted(glob.iglob('upload/*.log'), key=os.path.getctime)
sorted_list[-2]


来源:https://stackoverflow.com/questions/35364558/second-newest-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!