shutil is Python’s built-in module for copying files without installing anything extra. It is useful when combining picture directories while preserving the original files in case the copying program contains a bug. section 9.5.1
A duplicate-free directory merge separates the task into these steps:
- List files in each source directory with os.listdir. section 9.5.3
- Compare each candidate with files already in the target directory using filecmp.cmp. section 9.5.3
- Copy only nonidentical files with shutil.copy, generating a usable filename when a name already exists. section 9.5.3
- Test first on sample directories that do not contain valuable files, and avoid overwriting existing destinations. section 9.5.1 section 9.5.3
Merge two picture directories
make_copies(['pictures1', 'pictures2'], 'pictures_combined') checks every file from pictures1 and pictures2, compares it with files already in pictures_combined, and copies only files without identical matches. If a filename is already present, get_good_filename adds underscores before the .png extension. section 9.5.3
Listing 9.7 make_copy function for our pictures merge task
def make_copy(fname, target_dir):
'''
fname is a filename like pictures1/1262.png.
target_dir is the name of a directory. #2
#2
Compare the file fname to all files in target_dir. #2
If fname is not identical to any file in #2
target_dir, copy it to target_dir #2
''' #2
for target_fname in os.listdir(target_dir): #1
if filecmp.cmp(fname, os.path.join( \ #2
target_dir, target_fname)):
return #3
shutil.copy(fname, get_good_filename( #4
os.path.join(target_dir, \ #4
os.path.basename(fname)))) #4
Inspect the make_copy implementation to see how filecmp.cmp, os.listdir, shutil.copy, and generated destination names work together. section 9.5.3

