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?
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)
You may prefer to use pathlib nowadays. The solution is in a duplicate question. https://stackoverflow.com/a/70404383/1615108
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.