使用模式和修改的tim过滤文件

2024-04-24 12:32:50 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我使用下面的代码列出目录中的文件在最后一次修改时间

searchdir = args[0]

files = filter(os.path.isfile, os.listdir(searchdir)))
files = [os.path.join(searchdir, f) for f in files] 
files.sort(key=lambda x: os.path.getmtime(x))
print file 

我只想列出特定模式的文件以及最后修改的时间 如何在上面的代码中实现特定模式(文件名)搜索?我想要所有文件名都是Mtuberc?在

示例文件:

^{pr2}$

预期产量:

Mtuberc.log  
Mtuberc.log.1 
Mtuberc.log.16
Mtuberc.log.13

Tags: 文件path代码目录os文件名时间模式
1条回答
网友
1楼 · 发布于 2024-04-24 12:32:50

下面的代码查找与给定模式匹配的文件。使用的模式要求文件名以'Mtuberc.log.日志'. 在

import os
import re

searchdir = args[0]
pattern = re.compile(r'^Mtuberc\.log') # whatever you want to match
files = filter(os.path.isfile, os.listdir(searchdir))
files = [os.path.join(searchdir, f) for f in files if pattern.search(f)] 
files.sort(key=lambda x: os.path.getmtime(x))
print files

相关问题 更多 >