How to get the latest file in a folder using python

garlapak picture garlapak · Sep 5, 2016 · Viewed 155.9k times · Source

I need to get the latest file of a folder using python. While using the code:

max(files, key = os.path.getctime)

I am getting the below error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'a'

Answer

Marlon Abeykoon picture Marlon Abeykoon · Sep 5, 2016

Whatever is assigned to the files variable is incorrect. Use the following code.

import glob
import os

list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file