Python identifies the file with the highest number as part of the filename
I have files with a number appended at the end, for example:
file_01.csv
file_02.csv
file_03.csv
I'm looking for an easy way to identify the file with the largest number appended to it. Is there a moderately easy way to achieve this? ... I was thinking about importing all the filenames in a folder, extracting the last digits, converting to a number, and finding the maximum number, however this looks moderately difficult as I suppose it is a relatively general task.
+3
source to share
2 answers
if the filenames are indeed formatted in such a good way, you can simply use max
:
>>> max(['file_01.csv', 'file_02.csv', 'file_03.csv'])
'file_03.csv'
but please note that:
>>> 'file_5.csv' > 'file_23.csv'
True
>>> 'my_file_01' > 'file_123'
True
>>> 'fyle_01' > 'file_42'
True
so you can add some kind of check to your function and / or use glob.glob
:
>>> max(glob.glob('/tmp/file_??'))
'/tmp/file_03'
+7
source to share