Skip to content Skip to sidebar Skip to footer

Search For Sub-directory Python

I am attempting to automate the specification of a sub-directory which one of my scripts requires. The idea is to have the script search the C: drive for a folder of a specific na

Solution 1:

StopIteration is raised whenever an iterator has no more values to generate.

Why are you using os.walk(dir).next()[1]? Wouldn't it be easier to just do everything in a for loop? Like:

for root, dirs, files in os.walk(mydir):
    #dirs here should be equivalent to dirList

Here is the documentation for os.walk.

Solution 2:

What worked for me is specifying the full path in os.walk, rather than just the directory name:

# fullpath of the directory of interest with subfolders to be iterated (Mydir)fullpath = os.path.join(os.path.dirname(__file__),'Mydir')

# iterationsubfolders = os.walk(fullpath).next()[1]

This happened to me in particular when a module that contains os.walk is located in a subfolder itself, imported by a script in a parent folder.

Parent/
    script
    Folder/
        module
        Mydir/
            Subfolder1
            Subfolder2

In script, os.walk('Mydir') will look in Parent/Mydir, which does not exist.

On the other hand, os.walk(fullpath) will look in Parent/Folder/Mydir.

Post a Comment for "Search For Sub-directory Python"