简体   繁体   English

如何获取目录 Python 中最后 4 个修改的文件

[英]How to get the last 4 modified files in directory Python

I often need to parse through the logs of a messy application.我经常需要解析一个凌乱的应用程序的日志。 This application has many instances so many logs for each instance.这个应用程序有很多实例,每个实例都有很多日志。 For each instance of this application, I need to search the newest 4 files in each log directory to look for files, how can I achieve this?对于这个应用程序的每个实例,我需要在每个日志目录中搜索最新的 4 个文件来查找文件,我该如何实现呢? I know how to get the latest file but I don't know how to make it count back 4 times:我知道如何获取最新文件,但我不知道如何让它倒数 4 次:

list_of_files = glob.glob('D:\logs\Worker1\*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getmtime)

You're very close:你非常接近:

list_of_files = glob.glob(r'D:\logs\Worker1\*')
list_of_files.sort(key=os.path.getmtime)
newest = list_of_files[-4:]

Why don't you get all the modified times, sort them in descending order, and pick the first 4?为什么不获取所有修改时间,按降序排序,然后选择前 4 个?

Something like this:像这样的东西:

files_modified_list = [(f, os.path.getmtime(f)) for f in list_of_files]
sorted_files_modified_list = sorted(file_modified_list, key=lambda x: x[1])
top_4_latest_files = [f[0] for f in sorted_files_modified_list[0:3]]

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

相关问题 如何获取目录中最后修改的文件? - How to get last modified file in a directory? 使用Python获取目录(包括子目录)的最后修改日期? - Get the last modified date of a directory (including subdirectories) using Python? 使用 python 脚本获取目录中添加的删除和修改文件的列表 - To get list of added removed and modified files in directory using python script 无论如何要在过去 24 小时内修改文件而不遍历目录中的所有文件 - Is there anyway to get files modified in last 24 hours without looping through all files in directory 使用python最后修改的子目录 - Last modified sub directory using python 如何获取上次在Python中修改文件的时间? - How do I get the time a file was last modified in Python? Python etag /最后修改不起作用; 如何获得最新的RSS - Python etag/last modified not working; how to get latest rss 如何使用Python获取文件夹中上次修改文件的时间 - How to get the time of the last modified file in a folder using Python GAE Python:如何获取静态文件的最后修改日期 - GAE Python: how get last modified date of static file Python看门狗,当修改某些文件时,只创建一个修改过的目录 - Python watchdog, when certain files are modified only a directory modified is created
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM