【问题标题】:filter files with a pattern and modified time过滤具有模式和修改时间的文件
【发布时间】:2014-02-25 15:04:16
【问题描述】:

您好,我正在使用以下代码列出上次修改时间时目录中的文件

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 

我只想列出特定模式的文件以及最后修改时间 我怎样才能在上面的代码中获得特定的模式(文件名)搜索?我想要所有文件名为 Mtubrc 的文件?

示例文件:

streptococcous.log 
baccidius.log 
Mtuberc.log  
Mtuberc.log.1 
Mtuberc.log.16
Mtuberc.log.13

预期输出:

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

【问题讨论】:

  • 请标记您的问题:编程语言是什么?蟒蛇?
  • @Ali 是的,它在 Python 中
  • 好的,我看到你已经相应地标记了它。将来还请包括编程语言的标签,它将帮助您更快地获得答案,提高您问题的可见性。祝你好运!
  • 您可以使用glob module 仅列出符合您条件的文件,也可以使用fnmatch module 在您收集文件后过滤您的文件列表。

标签: python regex file filter


【解决方案1】:

下面的代码查找与给定模式匹配的文件。使用的模式要求文件名以“Mtubrc.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2011-07-21
    • 2011-06-21
    • 2022-01-19
    • 1970-01-01
    相关资源
    最近更新 更多