liveBook · Manning

Filecmp.cmp

As explained in Learn AI-Assisted Python Programming, Second Edition

filecmp.cmp is a Python function that compares two files and reports whether their contents appear equivalent under its comparison settings.

filecmp.cmp checks whether two files are identical, helping a file-copying task avoid duplicate files. section 9.5.3

A duplicate-aware copy function uses it in a simple sequence:

  • List the files already present in the target directory. section 9.5.3
  • Compare the input file with each target file using filecmp.cmp. section 9.5.3
  • Stop when an identical file is found; otherwise copy the input with shutil.copy. section 9.5.3

Merging picture directories

make_copy compares each file from pictures1 or pictures2 with every file in pictures_combined. It copies only files without an identical match, using a safe filename when needed. 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 complete make_copy implementation, including directory scanning, path construction, comparison, and conditional copying. section 9.5.3

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Shows its use inside a complete copying function, without explaining comparison internals.
Examples
Demonstrates comparing files from pictures1 and pictures2 before copying into pictures_combined.
What it assumes
Assumes basic Python functions, directories, filenames, and standard-library calls such as os.listdir and shutil.copy.
What you can do after
Apply it via Python to build a duplicate-aware file-copying function.
How it connects
Connects filecmp.cmp with os.listdir, os.path.join, and shutil.copy.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.