读取子文件夹python



我试图制作一个数据解析器,但在我的项目中使用了python,但每个文件都在一个单独的文件夹中。目前我能够读取第一个文件夹,但我还没有弄清楚如何在那之后读取文件夹并将其放入循环中

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)

最新更新