Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to copy files from one folder to another using Python?
Python provides several modules to copy files between folders. The most commonly used are shutil, os, and pathlib. Each offers different methods depending on whether you want to copy individual files or entire directories.
Using shutil.copy()
The shutil.copy() function copies a file from source to destination, preserving file permissions but not metadata ?
import shutil
import os
# Create source directory and file for demonstration
os.makedirs('source_folder', exist_ok=True)
with open('source_folder/sample.txt', 'w') as f:
f.write('Hello, this is a sample file!')
# Create destination directory
os.makedirs('destination_folder', exist_ok=True)
# Copy file from source to destination
shutil.copy('source_folder/sample.txt', 'destination_folder/sample.txt')
print("File copied successfully!")
print("Files in destination:", os.listdir('destination_folder'))
File copied successfully! Files in destination: ['sample.txt']
Using shutil.copy2()
The shutil.copy2() function copies files while preserving metadata like timestamps ?
import shutil
import os
from datetime import datetime
# Create a file with current timestamp
os.makedirs('source_folder', exist_ok=True)
with open('source_folder/document.txt', 'w') as f:
f.write('Document with metadata')
# Copy with metadata preservation
shutil.copy2('source_folder/document.txt', 'destination_folder/document.txt')
# Check file exists
if os.path.exists('destination_folder/document.txt'):
print("File copied with metadata preserved!")
print("File size:", os.path.getsize('destination_folder/document.txt'), "bytes")
File copied with metadata preserved! File size: 20 bytes
Copying Multiple Files
To copy all files from one folder to another, use shutil.copytree() or loop through files ?
import shutil
import os
# Create multiple files in source
os.makedirs('multi_source', exist_ok=True)
files = ['file1.txt', 'file2.txt', 'file3.txt']
for filename in files:
with open(f'multi_source/{filename}', 'w') as f:
f.write(f'Content of {filename}')
# Copy all files individually
os.makedirs('multi_destination', exist_ok=True)
for filename in os.listdir('multi_source'):
if os.path.isfile(f'multi_source/{filename}'):
shutil.copy2(f'multi_source/{filename}', f'multi_destination/{filename}')
print("All files copied!")
print("Destination files:", sorted(os.listdir('multi_destination')))
All files copied! Destination files: ['file1.txt', 'file2.txt', 'file3.txt']
Using pathlib (Modern Approach)
Python 3.4+ provides pathlib for more intuitive file operations ?
from pathlib import Path
import shutil
# Create paths
source_path = Path('source_folder')
dest_path = Path('pathlib_destination')
# Create directories and file
source_path.mkdir(exist_ok=True)
dest_path.mkdir(exist_ok=True)
sample_file = source_path / 'pathlib_sample.txt'
sample_file.write_text('Using pathlib for file operations')
# Copy using pathlib and shutil
dest_file = dest_path / 'pathlib_sample.txt'
shutil.copy2(sample_file, dest_file)
print(f"File copied from {sample_file} to {dest_file}")
print("File content:", dest_file.read_text())
File copied from source_folder/pathlib_sample.txt to pathlib_destination/pathlib_sample.txt File content: Using pathlib for file operations
Comparison
| Method | Preserves Metadata | Best For |
|---|---|---|
shutil.copy() |
Permissions only | Simple file copying |
shutil.copy2() |
All metadata | Exact file duplication |
shutil.copytree() |
Yes | Entire directory copying |
pathlib |
Depends on method used | Modern, readable code |
Conclusion
Use shutil.copy2() for single files with metadata preservation. Use shutil.copytree() for entire directories. Consider pathlib for more readable and modern Python code.
