Skip to content Skip to sidebar Skip to footer

Python Identify File With Largest Number As Part Of Filename

I have files with a number appended at the end e.g: file_01.csv file_02.csv file_03.csv I am looking for a simple way of identifying the file with the largest number appende

Solution 1:

if the filenames are really formatted in such a nice way, then you can simply use max:

>>> max(['file_01.csv', 'file_02.csv', 'file_03.csv'])
'file_03.csv'

but note that:

>>> 'file_5.csv' > 'file_23.csv'True>>> 'my_file_01' > 'file_123'True>>> 'fyle_01' > 'file_42'True

so you might want to add some kind of validation to your function, and/or or use glob.glob:

>>> max(glob.glob('/tmp/file_??'))
'/tmp/file_03'

Solution 2:

import re
x=["file_01.csv","file_02.csv","file_03.csv"]
printmax(x,key=lambda x:re.split(r"_|\.",x)[1])

Post a Comment for "Python Identify File With Largest Number As Part Of Filename"