liveBook · Manning

Shutil.copy

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

A Python function that copies a file to a destination while preserving the file's contents and basic metadata where supported.

shutil.copy copies a file into a destination directory. In a picture-merging task, it runs only after comparisons show that no identical file is already present. section 9.5.3

Copy only nonduplicate pictures

make_copy compares a source file with every file in the target directory, then calls shutil.copy with a generated destination path when no match exists. get_good_filename prevents a filename collision by adding underscores before the 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

The make_copy listing shows how file comparison, destination-path construction, collision handling, and shutil.copy fit together. section 9.5.3

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

How deep it goes
Shows the call within a complete helper function but does not explain shutil.copy internals.
Examples
Demonstrates copying pictures into pictures_combined after comparing files from pictures1 and pictures2.
What it assumes
Assumes basic Python functions, directories, filenames, and standard-library file operations.
What you can do after
Apply it via Python to copy selected files into a target directory after checking duplicates.
How it connects
Connects file copying with file comparison, directory listing, path construction, and filename collision handling.

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.