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
Feature | shutil.copy() | shutil.copytree() |
---|---|---|
Copies | One file only | Entire folder |
Destination | File path | New folder path |
Existing target | Can overwrite file | Target folder must not exist |
In summary, use copy()
for files and copytree()
for directories.