Home > Net >  Most recent file from a directory with Python
Most recent file from a directory with Python

Time:07-04

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

CodePudding user response:

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))
  • Related