Question

Can I somehow save the output of os.walk() in variables ? I tried basepath, directories, files = os.walk(path) but it didn't work. I want to proceed the files of the directory and one specific subdirectory. is this somehow possible ? Thanks

Was it helpful?

Solution

os.walk() returns a generator that will successively return all the tree of files/directories from the initial path it started on. If you only want to process the files in a directory and one specific subdirectory you should use a mix of os.listdir() and a mixture of os.path.isfile() and os.path.isdir() to get what you want.

Something like this:

def files_and_subdirectories(root_path):
    files = []
    directories = []
    for f in os.listdir(root_path):
        if os.path.isfile(f):
            files.append(f)
        elif os.path.isdir(f):
            directories.append(f)
    return directories, files

And use it like so:

directories,files = files_and_subdirectories(path)

OTHER TIPS

I want to proceed the files of the directory and one specific subdirectory. is this somehow possible ?

If that's all you want then simply try

[e for e in os.listdir('.') if os.path.isfile(e)] + os.listdir(special_dir)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top