Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get most recent file in a directory with certain extension

I'm trying to use the newest file in the 'upload' directory with '.log' extension to be processed by Python. I use a Ubuntu web server and file upload is done by a html script. The uploaded file is processed by a Python script and results are written to a MySQL database. I used this answer for my code.

import glob
newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)
print newest
f = open(newest,'r')

But this is not getting the newest file in the directory, instead it gets the oldest one. Why?

like image 622
Nilani Algiriyage Avatar asked Jun 10 '14 06:06

Nilani Algiriyage


2 Answers

The problem is that the logical inverse of max is min:

newest = max(glob.iglob('upload/*.log'), key=os.path.getctime)

For your purposes should be:

newest = min(glob.iglob('upload/*.log'), key=os.path.getctime)
like image 152
Jon Clements Avatar answered Nov 11 '22 15:11

Jon Clements


In many newer programs, it is preferred to use pathlib for this very common task:

from pathlib import Path

XLSX_DIR = Path('../../somedir/')
XLSX_PATTERN = r'someprefix*.xlsx'

latest_file = max(XLSX_DIR.glob(XLSX_PATTERN), key=lambda f: f.stat().st_ctime)
like image 1
dominecf Avatar answered Nov 11 '22 15:11

dominecf