Say I have a folder 'universe' in my F drive, in this folder, there are two sub folders 'dark_matter' and 'galaxy', and two text files. The sub folders contains more sub folders and files
What if I wanted to do something to all the files and folders inside of the universe folder. Basically what I want to do is walk down this directory and rename or copy or do something with all the contents in it. It can get tricky but python provides a function to walk down a tree.

In [1]:
import os
In [2]:
os.listdir('F:\\universe')
Out[2]:
['civilization.txt', 'dark_matter', 'galaxy', 'planet.txt']

os.walk()

The return value for this is used in for loops.
Unlike the range() function, it os.walk() returns 3 values.
The first value returned is the folder name, second value is list of strings for sub folders inside that folder, third value is the list strings for names of files inside that folder. It does that iteratively for all the folders.

In [3]:
os.walk('F:\\universe')
Out[3]:
<generator object walk at 0x000001EE5E84B6D0>
In [4]:
for folderName, subFolders, fileNames in os.walk('F:\\universe'):
    print('The folder is ' + folderName)
    print('The subFolders in ' + folderName +' are ' +str(subFolders))
    print('The filenames in ' + folderName +' are ' +str(fileNames))
    print()
The folder is F:\universe
The subFolders in F:\universe are ['dark_matter', 'galaxy']
The filenames in F:\universe are ['civilization.txt', 'planet.txt']

The folder is F:\universe\dark_matter
The subFolders in F:\universe\dark_matter are []
The filenames in F:\universe\dark_matter are ['unknown.txt']

The folder is F:\universe\galaxy
The subFolders in F:\universe\galaxy are []
The filenames in F:\universe\galaxy are []

If there is nothing, it returns a empyt list []



Example of what we can do with it is below

In [5]:
for folderName, subFolders, fileNames in os.walk('F:\\universe'):

    for subFolder in subFolders:
        if 'fish' in subFolder:
            os.rmdir(subfolder)

    for file in fileNames:
        if file.endswith('.py'):
            shutil.copy(os.path.join(folderName, file), os.path.join(folderName, file + '.backup')) #new extension