【问题标题】:How to grep specific extensions into list python3如何将特定扩展名grep到列表python3中
【发布时间】:2018-07-08 13:18:13
【问题描述】:

我有一个包含多个文件扩展名的目录,我想用 grep 将所有具有 2 个不同扩展名的文件的路径放入一个列表中。到目前为止,我已经尝试过:

my_files = list(Path(my_dir).glob('**/*.txt' and '**/*.txt.gz'))

但是使用上面的脚本,我只能得到 .txt.gz 文件的路径:

[PosixPath('/home/myproject/cd_4/M_1and2.txt.gz')]

我该如何解决?

【问题讨论】:

  • 'foo' and 'bar' 的计算结果为 'bar',您要么需要编写一个匹配两种情况的单一 glob 模式,要么为每种情况运行一次并加入结果。

标签: python python-3.x glob


【解决方案1】:

正如 cmets 中提到的,'ptrn1' and ptrn2' 总是评估为 'ptrn2'

所以你绝对不能通过一个glob 调用来做到这一点。对每个模式分别调用glob并合并结果

my_files  = list(Path('test').glob('**/*.txt'))
my_files += list(Path('test').glob('**/*.txt.gz'))

或作为单线

my_files = [p for ptrn in ['**/*.txt', '**/*.txt.gz'] for p in Path('test').glob(ptrn)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-31
    • 2010-11-29
    • 1970-01-01
    • 2019-01-27
    • 2020-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多