Skip to content
Advertisement

Second newest file

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement