我正在尝试循环子目录列表,并执行两个相关操作:
仅选择与特定模式匹配的子目录,并保存该名称的一部分
读取该子目录中的文件
我已尝试调整 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
isTrue
, the caller can modify thedirnames
list in-place (perhaps usingdel
or slice assignment), andwalk()
will only recurse into the subdirectories whose names remain indirnames
; this can be used to prune the search, impose a specific order of visiting, or even to informwalk()
about directories the caller creates or renames before it resumeswalk()
again.
关于python - 从特定目录中选择文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59331164/