Python get most recent file in a directory with certain extension

假如想象 提交于 2020-01-12 03:27:44

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/24134495/python-get-most-recent-file-in-a-directory-with-certain-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!