To write a program that can apply to a directory tree, Python needs to be able to navigate through a directory.
This is done via os.walk()
.
After moving into /files
:
In [1]:
import os
# Define base directory
defaultpath = os.path.expanduser('~/Dropbox/learn/books/Python/AutomateTheBoringStuffWithPython')
#Change directory to files directory if set in default
if (os.getcwd() == defaultpath):
os.chdir('/files')
else:
os.chdir(defaultpath + '/files')
import os
and use walk()
to return three values: [folderName, subfolders, filenames]
In [14]:
for folderName, subfolders, filenames in os.walk(os.getcwd()): # loop through all the variables returned from os.walk
print('The folder is ' + folderName + '\n') # Print folder name
print('The subfolders in ' + folderName + ' are ' + str(subfolders).join('\n,') + '\n') # Print subfolders
print('The filenames in ' + folderName + ' are ' + str(filenames).join('\n,') + '\n') # Print filenames
print('\n\n') # Double newline
It not only examines the parent folder, but loops through the entire subdirectory, and run functions accordingly:
In [21]:
import shutil
for folderName, subfolders, filenames in os.walk(os.getcwd()): # loop through all the variables returned from os.walk
for subfolder in subfolders: # for every subfolder
if 'fish' in subfolders: # if there is a subfolder named 'fish'
os.rmdir(subfolder) # delete it
else:
continue
# for every file in the walk
for file in filenames:
# that ends with .'py'
if file.endswith('.py'):
# backup files, but use use 'os.path.join' since files are just strings by themselves; need complete paths from cwd
shutil.copy(os.path.join(folderName, file), os.path.join(folderName, file) + '.backup')
This batch approaches allows us to run through an entire directory tree and run functions.
It is recommended to use dry-run mode with commented code first.
os.walk()
allows you to 'walk' through a directory tree, and interact with subdirectories and filenames.folderName
, subfolder
, and filename
.
In [ ]: