user6708857
user6708857

Reputation:

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.

Upvotes: 1

Views: 5152

Answers (1)

J Darbyshire
J Darbyshire

Reputation: 392

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])
    ...

Upvotes: 2

Related Questions