Python获取具有特定扩展名的目录中的最新文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24134495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:05:17  来源:igfitidea点击:

Python get most recent file in a directory with certain extension

pythonfilefile-io

提问by Nilani Algiriyage

I'm trying to use the newest file in the 'upload' directory with '.log' extension to be processed by Python. I use a Ubuntuweb 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 MySQLdatabase. I used thisanswer for my code.

我正在尝试使用“上传”目录中带有“.log”扩展名的最新文件,以便由 Python 处理。我使用Ubuntu网络服务器,文件上传是由 html 脚本完成的。上传的文件由 Python 脚本处理,并将结果写入MySQL数据库。我在我的代码中使用了这个答案。

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?

但这不是获取目录中最新的文件,而是获取最旧的文件。为什么?

采纳答案by Jon Clements

The problem is that the logical inverse of maxis min:

问题是 的逻辑逆maxmin

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)