【问题标题】:Why python glob.glob does not match any files with the wildcards I passed in?为什么 python glob.glob 与我传入的通配符不匹配任何文件?
【发布时间】:2019-01-14 19:28:49
【问题描述】:

例如:

20190108JPYUSDabced.csv
20190107JPYUSDabced.csv
20190106JPYUSDabced.csv

当我从终端搜索前 2 个文件时:

bash: ls /Users/Downloads/201901{08,07}JPYUSDabced.csv
it gives me the first 2 files (exclude 20190106JPYUSDabced.csv)

当我在 python 中做时:

import glob
glob.glob('/Users/Downloads/201901{08,07}JPYUSDabced.csv')
it gives me []

【问题讨论】:

标签: python glob


【解决方案1】:

根据glob 模块的文档,glob 底层使用fnmatch.fnmatchfnmatch 文档描述的唯一模式是:

Pattern   |    Meaning
--------- | -----------------------------
*         | matches everything 
?         | matches any single character 
[seq]     | matches any character in seq 
[!seq]    | matches any character not in seq 

对于文字匹配,将元字符括在括号中。例如,“[?]”匹配字符“?”。

尝试使用括号中的字符序列:

glob.glob('/Users/Downloads/2019010[87]JPYUSDabced.csv')

使用 os.walk

假设您要搜索特定日期范围,您可能需要尝试使用 os.walkre 正则表达式来获得您正在寻找的更复杂的模式。

警告:os.walk 从起始位置递归遍历每个目录,这可能不是您想要的。

您必须根据您的情况调整正则表达式,但这里有一个示例:

正则表达式匹配日期20181208 或日期20190107,但必须包含标识符JPYUSDabced.csv

regex = re.compile("(?:(?:20181208)|(?:20190107))JPYUSDabced.csv")

files = []
for dirpath, dirnames, filenames in os.walk('/Users/Downloads'):
    for f in filenames:
        if regex.match(f):
            files.append(os.path.join(dirpath, f))
print(files)
# ['/Users/Downloads/20190107JPYUSDabced.csv', '/Users/Downloads/20181208JPYUSDabced.csv']

【讨论】:

  • 实际情况更为复杂,即 [8,7] 不起作用。 20181208JPYUSDabced.csv 20190107JPYUSDabced.csv 20190106JPYUSDabced.csv 我想要前两个带有 glob.glob 的文件
  • @Maik 是您的真正目标:列出所有标有 2 个特定日期的文件?
  • 还要注意 glob.glob('/Users/Downloads/2019010[8,7]JPYUSDabced.csv') 也匹配 '/Users/Downloads/2019010,JPYUSDabced.csv'' 我认为这不是 OP 想要的。 匹配 seq 中的任何字符 仅表示“任何字符”(包括,,它恰好也是答案中的一个字符)。
  • @OndrejK。哎呀;你很准。删除了逗号。啊,我现在看到您首先将其编辑了。对此感到抱歉
  • 是的,我仍然担心它只适用于有问题的示例,但实际上 OP 可能需要 "{09,10}" 甚至更复杂的模式,并且不喜欢 [seq] 符号。我想 `os.walk() 之类的组合和正则表达式过滤器最终将成为解决方案。
猜你喜欢
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2011-03-19
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
  • 2013-02-03
相关资源
最近更新 更多