python second newest file

2019-08-12 16:34发布

问题:

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]