【问题标题】:Scanning subdirectories for files that match certain filenames扫描子目录以查找与特定文件名匹配的文件
【发布时间】:2022-12-11 07:27:56
【问题描述】:

我想扫描目录及其所有子目录中的某些文件名(即所有具有 .log 扩展名的文件,以及名称为 example1.txt 或 example2.txt 的所有文件),以便我可以进一步处理它们。我成功获取了所有以 .log 结尾的文件:

import re
from pathlib import Path

filenames = ["*.log", "example1.txt", "example2.txt"]

input_path = Path("./testfolder")
ls = [p for p in input_path.glob("**/*.log") if p.is_file()]
print(", ".join(str(p) for p in ls))

我需要做什么才能获得所有扩展名为 .log 的文件,以及所有名称为 example1.txt 或 example2.txt 的文件?

【问题讨论】:

    标签: python glob


    【解决方案1】:

    要扫描目录及其子目录以查找具有特定名称的文件,您可以使用 pathlib 模块中的 glob 方法并使用通配符模式指定要查找的文件名。

    import re
    from pathlib import Path
    
    # Define the file names you are looking for
    filenames = ["*.log", "example1.txt", "example2.txt"]
    
    # Define the input directory
    input_path = Path("./testfolder")
    
    # Use the glob method to search for files with the specified names
    files = [p for name in filenames for p in input_path.glob("**/{}".format(name)) if p.is_file()]
    
    # Print the list of matching files
    print(", ".join(str(p) for p in files))
    

    在此代码中,为文件名列表中的每个文件名调用一次 glob 方法。此方法在 input_path 目录及其子目录中搜索具有指定名称的文件。然后将生成的文件列表连接成一个列表并打印。

    【讨论】: