What is the difference between shutil.copy() and shutil.copytree()?

Python’s shutil module provides both copy() and copytree() for copying, but they serve different purposes.


1. shutil.copy()

  • Purpose: Copies a single file.
  • Syntax: shutil.copy(source_file, destination_file)
  • Use case: When you want to copy just one file to a new location.

Example:

import shutil
shutil.copy('data.txt', 'backup/data.txt')

This copies data.txt to the backup folder.


2. shutil.copytree()

  • Purpose: Copies a whole folder (directory) along with all its files and subfolders.
  • Syntax: shutil.copytree(source_folder, destination_folder)
  • Use case: When you want to create a full backup or duplicate of a directory.

Example:

shutil.copytree('project', 'project_backup')

This copies the entire project folder to project_backup.


Key Differences

Featureshutil.copy()shutil.copytree()
CopiesOne file onlyEntire folder
DestinationFile pathNew folder path
Existing targetCan overwrite fileTarget folder must not exist

In summary, use copy() for files and copytree() for directories.

Leave a Reply

Your email address will not be published. Required fields are marked *