'Get the latest file in every directory using python

I want find the latest zip file in every directory in a current working directory. I have this code that can find the latest file in one folder:

import glob
import os

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

How can I find the latest file in all folders?



Solution 1:[1]

Python 3.5+:

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.


For old versions:

Python 2.2+:

import fnmatch
import os

list_of_files = []
for root, dirnames, filenames in os.walk('/path/to/folder'):
    for filename in fnmatch.filter(filenames, '*.zip'):
        matches.append(os.path.join(root, filename))
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

Solution 2:[2]

Because I can't comment, the previous answer should read:

Python 2.2+:

import fnmatch
import os

list_of_files = []
for root, dirnames, filenames in os.walk('/path/to/folder'):
    for filename in fnmatch.filter(filenames, '*.zip'):
        list_of_files.append(os.path.join(root, filename))
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gulzar
Solution 2 Ted