Python: os.chdir() not working within a for loop?
Question: I'm trying to get a homemade path navigation function working - basically I
need to go through one folder, and explore every folder within it, running a
function within each folder.

I reach a problem when I try to change directories within a for loop. I've got
this "findDirectories" function:

    
    
    def findDirectories(list):
        for files in os.listdir("."):
            print (files)
            list.append(files)
            os.chdir("y")
    

That last line causes the problems. If I remove it, the function just compiles
a list with all the folders in that folder. Unfortunately, this means I have
to run this each time I go down a folder, I can't just run the whole thing
once. I've specified the folder "y" as that's a real folder, but the program
crashes upon opening even with that. Doing os.chdir("y") outside of the for
loop has no issues at all.

I'm new to Python, but not to programming in general. How can I get this to
work, or is there a better way? The final result I need is running a Function
on each single "*Response.xml" file that exists within this folder, no matter
how deeply nested it is.


Answer: Well, you don't post the traceback of the actual error but clearly it doesn't
work as you have specified `y` as a relative path.

Thus it may be able to change to `y` in the first iteration of the loop, but
in the second it will be trying to change to a **subdirectory** of `y` that is
also called `y`

Which you probably do not have.

You want to be doing something like

    
    
    import os
    
    for dirName, subDirs, fileNames in os.walk(rootPath):
        # its not clear which files you want, I assume anything that ends with Response.xml?
        for f in fileNames:
            if f.endswith("Response.xml"):
                # this is the path you will want to use
                filePath = os.path.join(dirName, f)
    
                # now do something with it!
                doSomethingWithFilePath(filePath)
    

Thats untested, but you have the idea ...

