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.
import os
os.listdir('F:\\universe')
os.walk('F:\\universe')
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()
If there is nothing, it returns a empyt list []
Example of what we can do with it is below
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