从特定目录中选择文件

问题描述 投票:1回答:2

我试图遍历子目录列表,并执行两个相关操作:

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

  • 读取该子目录中的文件

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

我的文件结构如下:

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

我只希望以“ normal”结尾的目录。然后,我将在该目录中读取名为“ 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)

我正在尝试遍历子目录列表,并执行两个相关操作:仅选择与特定模式匹配的子目录,并保存该名称的一部分,然后在其中读取文件...

python directory path glob
2个回答
1
投票

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


1
投票
import os
root_dir = "/Users/adamg/IM-logs"
for subdir, dirs, files in os.walk(root_dir):
    if str(subdir).endswith("normal"):
        for file in files:
            if str(file).startswith("names"):
                print(os.path.basename(subdir), file)
                f = open(os.path.join(root_dir,subdir,file), "r") 
                print(f.read())
© www.soinside.com 2019 - 2024. All rights reserved.