python - 从特定目录中选择文件

标签 python directory path glob

我正在尝试循环子目录列表,并执行两个相关操作:

  • 仅选择与特定模式匹配的子目录,并保存该名称的一部分

  • 读取该子目录中的文件

我已尝试调整 this question 中的答案但我无法仅打开某些子目录。我知道我可以递归地执行此操作,循环遍历每个文件,并使用 Path.parent 提取其父目录,但这也会进入我不感兴趣的目录。

我的文件结构如下:

002normal
|- names.txt
|- test.txt
002custom
|- names.txt
|- test.txt

我只想要以“正常”结尾的目录。然后我将读取该目录中名为“names.txt”的文件。我尝试过类似下面的方法,但没有运气。

import os
root_dir = "/Users/adamg/IM-logs"
for subdir, dirs, files in os.walk(root_dir):
    for f in files:
        print(subdir)

最佳答案

您可以就地修改 dirs 列表,以过滤掉名称不以 'normal' 结尾的任何子目录,以便 os.walk 不会遍历它们:

for subdir, dirs, files in os.walk(root_dir):
    dirs[:] = (name for name in dirs if name.endswith('normal'))
    if 'names.txt' in files:
        with open(os.path.join(subdir, 'names.txt')) as file:
            print(os.path.basename(subdir), file.read())

摘自os.walk的文档:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again.

关于python - 从特定目录中选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331164/

相关文章:

java - 如何打开整个MP3目录?

file - Go (golang) 由几个文件夹组成的包

C#include pbl.h路径

python - 如何将新的键值对添加到字典列表中的现有键值对?

python - PyTorch 中神经网络推理时间的波动

python - 如何使用 SQLAlchemy 复制 Oracle 中的唯一约束?

c# - CheckedListBox - 如何以编程方式确保在任何给定时间只能选中一项?

bash - 使用 Bash 将给定当前目录的绝对路径转换为相对路径

ruby - 在没有 RVM 的情况下更改 Ruby 路径

python - 模块未找到错误 : No module named 'pip.commands'