S.McGuire S.McGuire - 4 days ago 4
Python Question

Python: For each directory in the working directory go into that directory and get the name of the directory

I need to make a script that will iterate through all the directories inside a directory. It should go into each directory, get its name and save it to a variable and comes back out, and then loops.

for dir in os.walk(exDir):
path = dir
os.chdir(path)
source = #dir trimmed to anything after the last /
os.chdir("..")
loops


It needs to go into the directory to do other things not mentioned above. I've only just started Python and have been stuck on this problem for the last day or so.

Answer

For each iteration of your for loop, dir is a tuple of format (filepath, subdirectories, files). As such dir[0] will give you the filepath.

It sounds like you just want to os.chdir for each folder recursively in exDir in which case the following will work:

for dir in os.walk(exDir):
    os.chdir(dir[0])
    ...
Comments