Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 appended to it. Is there a moderately simple way of achieving this? ... I was thinking of importing all file names in the folder, extracting the last digits, converting to number, and then looking for max number, however that seems moderately complicated for what I assume is a relatively common task.

like image 334
kyrenia Avatar asked Jan 09 '23 08:01

kyrenia


1 Answers

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'
like image 91
ch3ka Avatar answered Jan 16 '23 22:01

ch3ka