silverds
silverds

Reputation: 21

How to get the latest file in a subdirectories with python?

I have a root directory with 5-6 subdirectories, inside this subdirectories i have 9-10 files, and i want a list with the last file for each subdirectories.

The structure is like that:

Structure

I want a list like: [File2, File4]

Ill try that:

list_files = glob.glob("root/*/*")
print(list_files)

And then use max function, but is not worked.

Any ideas?

Upvotes: 2

Views: 667

Answers (1)

applesomthing
applesomthing

Reputation: 367

Try putting this in a loop

import glob

list_of_files = glob.glob('/path/to/folder/**/*.zip', recursive=True)
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)

Quoting the documentation for glob.glob:

If recursive is true, the pattern ** will match any files and zero or more directories and subdirectories. If the pattern is followed by an os.sep, only directories and subdirectories match.

Upvotes: 3

Related Questions