How to check the latest file in a folder with Python?

4

Assuming you have a folder with several TXT files with different names and need to know the latest file, how do I do this using Python?

    
asked by anonymous 20.04.2018 / 14:13

1 answer

4

You can use the pathlib module.

from pathlib import Path

data_criacao = lambda f: f.stat().st_ctime
data_modificacao = lambda f: f.stat().st_mtime

directory = Path('/seu/diretorio')
files = directory.glob('*.txt')
sorted_files = sorted(files, key=data_modificacao, reverse=True)

for f in sorted_files:
    print(f)

This will display the name of the files in order of modification, from the last modified to the first. If you want to use the creation date, change to st_ctime , using data_criacao in key .

    
20.04.2018 / 14:28