Jay
Jay

Reputation: 291

Python return filepath/filename of most recent csv file stored in directory

I have a folder that csv files are stored in. How can I get python to search this folder and return the filename of the most recent file created. e.g search C:\CSVfiles and return filename in the form of C:\CSVfiles\CSVmostrecent.csv? I'm using windows.

Upvotes: 1

Views: 1540

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 602145

You can use the key parameter to the max() function:

import os
import glob

filename = max(glob.iglob("c:/csvfiles/*.csv"), key=os.path.getmtime)

Depending on your intention, you might want to use os.path.getctime instead of os.path.getmtime.

Upvotes: 6

Related Questions