3
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

simone100
  • 43
  • 1
  • 6
  • 1
    Regex? `re.findall(r"\d+", file_name)` or `re.findall(r"(\d{4})(\d{2})(\d{2})", file_name)` – 001 Jun 28 '22 at 13:59

1 Answers1

3

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))
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59