简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM