读取子文件夹python

读取子文件夹python,python,directory,Python,Directory,我正在尝试制作一个数据解析器,但是我的项目使用python,但是每个文件都在一个单独的文件夹中,彼此相连。目前,我能够读取第一个文件夹,但我还不知道如何读取文件夹后,把它放在一个for循环 import os r_path='//esw-fs01/esw_niagara_no_bck/BuildResults/master/0.1.52.68_390534/installation_area/autotestlogs_top/' sd_path='/.' root = os.listdir

我正在尝试制作一个数据解析器,但是我的项目使用python,但是每个文件都在一个单独的文件夹中,彼此相连。目前,我能够读取第一个文件夹,但我还不知道如何读取文件夹后,把它放在一个for循环

import os 

r_path='//esw-fs01/esw_niagara_no_bck/BuildResults/master/0.1.52.68_390534/installation_area/autotestlogs_top/'
sd_path='/.'

root = os.listdir(r_path)
subdir=os.listdir(sd_path)
for entry in root:
    # print(entry)
    if os.path.isdir(os.path.join(r_path, entry)):
        for subentry in subdir:
            if os.path.isdir(os.path.join(r_path,'/ConfigurationsTest_19469')):
                print(subentry)

对于第二个For循环,我想迭代autotestlogs文件夹中的每个文件夹。我试着去做,但显然不行。请帮忙谢谢

我想你把订单弄乱了一点。如果在循环之前执行
subdir=os.listdir(sd_path)
,则可能无法获取子目录,因为需要使用父目录来获取它们

因此,在循环中,在检查“条目”是否为文件夹后,可以将该文件夹的绝对路径存储在变量中,然后使用os.listdir()列出其内容。 然后,您可以循环使用它们并解析它们

我会怎么做:

import os

r_path='//esw-fs01/esw_niagara_no_bck/BuildResults/master/0.1.52.68_390534/installation_area/autotestlogs_top/'

root = os.listdir(r_path)

for entry in root:
    # print(entry)
    subdir_path = os.path.join(r_path, entry) #  create the absolute path of the subdir
    if os.path.isdir(subdir_path):  # check if it is a folder
        subdir_entries = os.listdir(subdir_path)  # get the content of the subdir
        for subentry in subdir_entries:
            subentry_path = os.path.join(subdir_path, subentry)  # absolute path of the subentry
            # here you can check everything you want for example if the subentry has a specific name etc
            print(subentry_path)

看看os.walk,例如os.walk(r_路径)中的根目录、子文件夹和文件:我想如果我想更深入,我需要再次循环另一个子目录条目?谢谢你,没错:)没问题!