Python在一个具有特定扩展名的目录中获取最新的文件 [英] Python get most recent file in a directory with certain extension
本文介绍了Python在一个具有特定扩展名的目录中获取最新的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图使用'.log'扩展名的'upload'目录中的最新文件由Python进行处理。我使用 Ubuntu
web服务器,文件上传是通过html脚本完成的。上传的文件由Python脚本处理,结果写入 MySQL
数据库。我为我的代码使用了这个答案。 p>
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?
推荐答案
问题在于 max
的逻辑逆是 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)
这篇关于Python在一个具有特定扩展名的目录中获取最新的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文