0

Im trying to make a data parser but using python for my project but each files are inside a separate folders to each other. Currently i am able to read the first folder but i havent figured out how to read the folder after that and put it in a for loop

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 the second for loop, i want to iterate every folder that are in autotestlogs folder. i tried to make it but it doesnt work apparently. Please help Thanks

1
  • Have a look at os.walk, e.g., for root, subFolders, files in os.walk(r_path): Commented Jun 9, 2021 at 8:24

1 Answer 1

1

I think you messed your order up a little bit. If you do subdir = os.listdir(sd_path) before the loop you can't possibly get the sub directories because you need to use the parent directory to get to them.

So in your loop after you checked that an "entry" is a folder you can store the absolute path of this folder in a variable and then list it's contents with os.listdir(). Then you can loop through those and parse them.

How I would do it:

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)
Sign up to request clarification or add additional context in comments.

1 Comment

and i presume if i want to go even deeper i need to make another subdir_entries loop again? thank you btw

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.