简体   繁体   English

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

[英]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.我正在尝试使用“上传”目录中带有“.log”扩展名的最新文件,以便由 Python 处理。 I use a Ubuntu web server and file upload is done by a html script.我使用Ubuntu Web 服务器,文件上传是由 html 脚本完成的。 The uploaded file is processed by a Python script and results are written to a MySQL database.上传的文件由 Python 脚本处理,结果写入MySQL数据库。 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 : 问题是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)

You may prefer to use pathlib nowadays.现在您可能更喜欢使用 pathlib。 The solution is in a duplicate question.解决方案是在一个重复的问题中。 https://stackoverflow.com/a/70404383/1615108 https://stackoverflow.com/a/70404383/1615108

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM