- shutil.copy() — copy file with permissions
- shutil.copy2() — copy with metadata
- shutil.copyfile() — copy file content only
- copy() vs copy2() — understanding the difference
- Batch copying — copying multiple files
- Error handling — robust file copying
Copying Files in Python
Copying files is a common operation when you need to create backups, duplicate data, or organize files. Python's shutil module provides several functions to copy files, each with different features.
Think of copying a file like making a photocopy of a document. The original stays untouched, and you get an exact duplicate. Python gives you several ways to make these copies, depending on what you need to preserve.
💡 Key concept: The shutil module (shell utilities) provides high-level file operations. For copying files, it offers three main functions: copy(), copy2(), and copyfile(). Each serves a different purpose.
shutil.copy()
Copy with Permissions
# The shutil.copy() function copies the file and its permissions
import shutil
import os
# Create a sample file
with open("original.txt", "w") as f:
f.write("This is the original file.\n")
f.write("We will copy this file.\n")
# 1. Basic copy
shutil.copy("original.txt", "copy.txt")
print("Copied: original.txt → copy.txt")
# 2. Copy to a different directory
# First create a directory
os.makedirs("backup", exist_ok=True)
shutil.copy("original.txt", "backup/original.txt")
print("Copied: original.txt → backup/original.txt")
# 3. Copy with a new name in a different directory
shutil.copy("original.txt", "backup/backup_copy.txt")
print("Copied: original.txt → backup/backup_copy.txt")
# 4. Verify the copy
with open("copy.txt", "r") as f:
content = f.read()
print("Content of copy.txt:")
print(content)
# 5. Check permissions
import stat
original_perms = os.stat("original.txt").st_mode
copy_perms = os.stat("copy.txt").st_mode
print(f"Original permissions: {oct(original_perms)}")
print(f"Copy permissions: {oct(copy_perms)}")
shutil.copy() key points:
- Copies content — file content is duplicated
- Copies permissions — file permissions are preserved
- Destination can be directory — copies with same name
- Destination can be file — copies with new name
- Returns path — returns the path to the copied file
Quick Check: What does shutil.copy() preserve? (Answer: File content and permissions)
shutil.copy2()
Copy with All Metadata
# shutil.copy2() copies the file with all metadata
import shutil
import os
import time
# Create a file with specific metadata
with open("source.txt", "w") as f:
f.write("This file has metadata.\n")
f.write("We'll copy it with copy2().\n")
# Get original metadata
original_stat = os.stat("source.txt")
print(f"Original last modified: {time.ctime(original_stat.st_mtime)}")
# Wait a moment to ensure timestamps differ
time.sleep(1)
# Copy with copy2()
shutil.copy2("source.txt", "metadata_copy.txt")
print("Copied: source.txt → metadata_copy.txt")
# Check copied metadata
copy_stat = os.stat("metadata_copy.txt")
print(f"Copy last modified: {time.ctime(copy_stat.st_mtime)}")
# Compare with shutil.copy()
shutil.copy("source.txt", "simple_copy.txt")
simple_stat = os.stat("simple_copy.txt")
print(f"Simple copy last modified: {time.ctime(simple_stat.st_mtime)}")
# copy2() preserves timestamps, copy() does not
shutil.copy2() key points:
- Copies all metadata — timestamps, permissions, etc.
- Preserves timestamps — creation and modification times
- More complete — best for exact duplicates
- Slightly slower — due to copying extra metadata
Quick Check: What additional metadata does copy2() preserve? (Answer: Timestamps and file metadata)
shutil.copyfile()
Copy File Content Only
# shutil.copyfile() copies only the file content
import shutil
# Create a source file
with open("source_data.txt", "w") as f:
f.write("This file contains important data.\n")
f.write("We'll copy the content only.\n")
# 1. Basic copyfile
shutil.copyfile("source_data.txt", "content_copy.txt")
print("Copied content: source_data.txt → content_copy.txt")
# 2. Verify content
with open("content_copy.txt", "r") as f:
content = f.read()
print("Content of copy:")
print(content)
# 3. copyfile() requires the destination to be a file
# It cannot copy to a directory
# 4. Check if files are identical
import filecmp
if filecmp.cmp("source_data.txt", "content_copy.txt"):
print("Files are identical!")
else:
print("Files are different!")
# 5. copyfile() vs copy()
# copyfile() - only content
# copy() - content + permissions
shutil.copyfile() key points:
- Content only — copies file content only
- No metadata — does not preserve permissions or timestamps
- Destination must be file — cannot copy to a directory
- Fastest method — least overhead
Quick Check: What does shutil.copyfile() copy? (Answer: Only the file content)
copy() vs copy2()
Choosing the Right Copy Function
# Comparison of copy functions
import shutil
import os
import time
# Create a test file
with open("test.txt", "w") as f:
f.write("Test file for comparing copy methods.\n")
f.write("We'll see the differences in metadata preservation.\n")
# Get original metadata
orig_stat = os.stat("test.txt")
print("=== Original File ===")
print(f"Size: {orig_stat.st_size} bytes")
print(f"Last modified: {time.ctime(orig_stat.st_mtime)}")
print(f"Permissions: {oct(orig_stat.st_mode)}\n")
# Wait to ensure timestamps differ
time.sleep(1)
# Copy using different methods
shutil.copy("test.txt", "copy_method.txt")
shutil.copy2("test.txt", "copy2_method.txt")
shutil.copyfile("test.txt", "copyfile_method.txt")
print("=== After Copying ===")
# Check copy() result
copy_stat = os.stat("copy_method.txt")
print("1. shutil.copy()")
print(f" Size: {copy_stat.st_size} bytes")
print(f" Modified: {time.ctime(copy_stat.st_mtime)}")
print(f" Permissions: {oct(copy_stat.st_mode)}\n")
# Check copy2() result
copy2_stat = os.stat("copy2_method.txt")
print("2. shutil.copy2()")
print(f" Size: {copy2_stat.st_size} bytes")
print(f" Modified: {time.ctime(copy2_stat.st_mtime)}")
print(f" Permissions: {oct(copy2_stat.st_mode)}\n")
# Check copyfile() result
copyfile_stat = os.stat("copyfile_method.txt")
print("3. shutil.copyfile()")
print(f" Size: {copyfile_stat.st_size} bytes")
print(f" Modified: {time.ctime(copyfile_stat.st_mtime)}")
print(f" Permissions: {oct(copyfile_stat.st_mode)}")
print("\n=== Summary ===")
print("copy() - copies content + permissions")
print("copy2() - copies content + permissions + timestamps")
print("copyfile() - copies content only")
Comparison summary:
- copy() — content + permissions (best for backups)
- copy2() — content + permissions + timestamps (exact duplicate)
- copyfile() — content only (fastest)
Quick Check: Which function creates the most complete copy? (Answer: shutil.copy2())
Batch Copying Files
Copying Multiple Files
import shutil
import os
# Create sample files
for i in range(3):
with open(f"file_{i}.txt", "w") as f:
f.write(f"Sample file {i}\n")
f.write("Created for batch copy demonstration.\n")
# 1. Copy all files in a directory to a backup folder
def backup_files(source_dir, backup_dir):
"""Copy all files from source to backup directory"""
os.makedirs(backup_dir, exist_ok=True)
for filename in os.listdir(source_dir):
source_path = os.path.join(source_dir, filename)
if os.path.isfile(source_path):
dest_path = os.path.join(backup_dir, filename)
shutil.copy2(source_path, dest_path)
print(f"Copied: {filename} → {backup_dir}/")
backup_files(".", "backup_files")
# 2. Copy files matching a pattern
def copy_matching_files(source_dir, dest_dir, pattern):
"""Copy files matching a pattern"""
os.makedirs(dest_dir, exist_ok=True)
for filename in os.listdir(source_dir):
if pattern in filename and os.path.isfile(os.path.join(source_dir, filename)):
source_path = os.path.join(source_dir, filename)
dest_path = os.path.join(dest_dir, filename)
shutil.copy2(source_path, dest_path)
print(f"Copied: {filename} → {dest_dir}/")
copy_matching_files(".", "pattern_files", "file_")
# 3. Copy with progress tracking
def copy_with_progress(source, dest):
"""Copy a file with progress indication"""
import time
source_size = os.path.getsize(source)
copied = 0
with open(source, 'rb') as src, open(dest, 'wb') as dst:
while True:
chunk = src.read(1024 * 1024) # 1MB chunks
if not chunk:
break
dst.write(chunk)
copied += len(chunk)
progress = (copied / source_size) * 100
print(f"Progress: {progress:.1f}%", end='\r')
print() # New line after progress
print(f"Copy complete: {source} → {dest}")
# 4. Copy with verification
def copy_with_verification(source, dest):
"""Copy and verify the file was copied correctly"""
shutil.copy2(source, dest)
import filecmp
if filecmp.cmp(source, dest):
print(f"✅ Verified: {source} and {dest} are identical")
return True
else:
print(f"❌ Verification failed: {source} and {dest} differ")
return False
Batch copying strategies:
- All files — copy every file in a directory
- Pattern matching — copy only files matching a pattern
- Progress tracking — monitor copy progress
- Verification — confirm files were copied correctly
Quick Check: Why would you verify a file after copying? (Answer: To ensure the copy was successful and accurate)
Error Handling When Copying
Robust File Copying
import shutil
import os
# 1. Comprehensive copy function
def safe_copy(source, destination):
"""Safely copy a file with error handling"""
try:
# Check if source exists
if not os.path.exists(source):
print(f"Error: Source '{source}' does not exist")
return False
# Check if source is a file
if not os.path.isfile(source):
print(f"Error: '{source}' is not a file")
return False
# Check if destination directory exists
dest_dir = os.path.dirname(destination)
if dest_dir and not os.path.exists(dest_dir):
os.makedirs(dest_dir, exist_ok=True)
print(f"Created directory: {dest_dir}")
# Perform the copy
shutil.copy2(source, destination)
print(f"Copied: {source} → {destination}")
return True
except PermissionError:
print(f"Error: Permission denied when copying '{source}'")
return False
except OSError as e:
print(f"Error: {e}")
return False
except Exception as e:
print(f"Unexpected error: {e}")
return False
# 2. Copy with automatic backup
def copy_with_backup(source, destination):
"""Copy a file with automatic backup of existing file"""
if os.path.exists(destination):
backup = destination + ".backup"
shutil.copy2(destination, backup)
print(f"Existing file backed up as: {backup}")
return safe_copy(source, destination)
# 3. Copy with confirmation
def copy_with_confirm(source, destination):
"""Copy a file with user confirmation"""
if os.path.exists(destination):
print(f"Warning: '{destination}' already exists")
response = input("Overwrite? (y/n): ")
if response.lower() != 'y':
print("Copy cancelled")
return False
return safe_copy(source, destination)
Common copy errors:
- FileNotFoundError — source file doesn't exist
- PermissionError — can't read source or write destination
- IsADirectoryError — trying to copy a directory as a file
- Always handle errors — make your code robust
Quick Check: What error occurs when you try to copy a file you don't have permission to read? (Answer: PermissionError)
Best Practices for Copying Files
Professional File Copying Guidelines
import shutil
import os
# 1. Always check if source exists
def smart_copy(source, destination):
"""Copy with existence checks"""
if not os.path.exists(source):
print(f"Cannot copy: '{source}' does not exist")
return False
if os.path.exists(destination):
print(f"Warning: '{destination}' will be overwritten")
try:
shutil.copy2(source, destination)
return True
except Exception as e:
print(f"Error: {e}")
return False
# 2. Use the right copy function
# For backups: shutil.copy2() - preserves everything
# For quick copies: shutil.copy() - preserves permissions
# For content only: shutil.copyfile() - fastest
# 3. Create destination directories if needed
def copy_with_dirs(source, destination):
"""Copy and create destination directory if needed"""
dest_dir = os.path.dirname(destination)
if dest_dir and not os.path.exists(dest_dir):
os.makedirs(dest_dir, exist_ok=True)
print(f"Created directory: {dest_dir}")
return smart_copy(source, destination)
# 4. Use filecmp for verification
def verified_copy(source, destination):
"""Copy and verify the result"""
if smart_copy(source, destination):
import filecmp
if filecmp.cmp(source, destination):
print(f"Copy verified: {source} and {destination} match")
return True
else:
print(f"Warning: Copy verification failed for {destination}")
return False
return False
# 5. Copy large files efficiently
def copy_large_file(source, destination):
"""Copy large files in chunks to save memory"""
try:
with open(source, 'rb') as src, open(destination, 'wb') as dst:
while True:
chunk = src.read(1024 * 1024) # 1MB chunks
if not chunk:
break
dst.write(chunk)
print(f"Copy complete: {source} → {destination}")
return True
except Exception as e:
print(f"Error: {e}")
return False
Best practices summary:
- Check source — verify file exists before copying
- Use right function — copy(), copy2(), or copyfile()
- Create directories — ensure destination exists
- Verify copies — confirm files are identical
- Handle errors — make your code robust
Quick Check: What is the most important check before copying a file? (Answer: Verify the source file exists)
Try It Yourself
Experiment with copying files in the editor below. Try different copy methods and see the results.
COPY FILE PRACTICE
========================================
1. CREATING SAMPLE FILE
✅ Created: sample.txt
2. SHUTIL.COPY()
✅ Copied: sample.txt → copy1.txt
3. SHUTIL.COPY2()
✅ Copied: sample.txt → copy2.txt
4. SHUTIL.COPYFILE()
✅ Copied: sample.txt → copy3.txt
5. COPY TO DIRECTORY
✅ Copied: sample.txt → backup/sample_backup.txt
6. VERIFYING COPIES
✅ copy1.txt matches original
✅ copy2.txt matches original
✅ copy3.txt matches original
Copy file practice complete!
You've Got It!
You now know multiple ways to copy files in Python. You understand the differences between copy(), copy2(), and copyfile(), and how to handle errors professionally.
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between copy() and copy2()?
What is the difference between copy() and copyfile()?
Can I copy a file to a different directory?
shutil.copy(source, "destination_directory/") to copy to a directory. The file will keep its original name. To change the name, specify the full path: shutil.copy(source, "destination_directory/new_name.txt").
What's a common interview question about file copying?
How do I copy a large file efficiently?
What happens if the destination file already exists?
Where to Go From Here
Now that you can copy files, check out these related topics:
Move File
Learn how to move files between directories.
Learn More →List Files in Directory
Learn how to list and filter files.
Learn More →Binary Files
Learn how to read and write binary files.
Learn More →