Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most recent file from a directory with Python

import os
fish=os.listdir("H:\Comu\Solo")
print(fish)

The result is:['lamba_20081104.pdf', 'conal_20070918.pdf', 'apialas_20220628.pdf']

the result is a list of the three file in the directory and my wished final result is: 20220628

I am not able to proceed...

The characters of the file to be taken are from -12 to -4

The result represents the date of the younger file (28.06.2022) in the directory "H:\Comu\Solo", because the number are date! In contrast with Ruby - Get the second most recent file from a directory?, in my case is the name-code of the file that suggests me the date!

Someone can write the script to obtain 20220628?

thank you very much

like image 1000
simone100 Avatar asked Jun 08 '26 11:06

simone100


1 Answers

Try this in one line:

max(fish, key=lambda x: x.split("_")[1].split(".")[0])

Python max accepts an argument(key) that will return your custom max function.

as @sniperd said,you can also use regex in the key:

max(l, key=lambda x: re.findall(r"\d+", x))
like image 154
Mehrdad Pedramfar Avatar answered Jun 10 '26 04:06

Mehrdad Pedramfar