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:
JavaScript
x
2
1
newest = min(glob.iglob('upload/*.log'), key=os.path.getctime)
2
However, how can I get not the min or max but the second element?
Advertisement
Answer
I think this can be a suitable solution:
JavaScript
1
9
1
# for the min + 1
2
sorted(glob.iglob('*.log'), key=os.path.getctime)[1]
3
4
# for the newest
5
sorted(glob.iglob('*.log'), key=os.path.getctime)[-1]
6
7
# for the second newest ( max - 1)
8
sorted(glob.iglob('*.log'), key=os.path.getctime)[-2]
9
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.