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 certain files from one folder to another using Python?
When working with files in Python, we often need to copy only certain types of files from one folder to another. Python provides several built-in modules like os, shutil, and pathlib to make this task simple and flexible.
Using shutil and os Modules
The shutil module performs high-level file operations like copying, moving, and archiving, while the os module handles operating system interactions for file and directory manipulation.
Copying Files by Extension
Here's how to copy all .txt files from a source folder to a destination folder ?
import os
import shutil
# Create sample files for demonstration
os.makedirs('source_dir', exist_ok=True)
os.makedirs('dest_dir', exist_ok=True)
# Create some sample files
with open('source_dir/file1.txt', 'w') as f:
f.write('This is file 1')
with open('source_dir/file2.txt', 'w') as f:
f.write('This is file 2')
with open('source_dir/image.png', 'w') as f:
f.write('This is an image file')
source_folder = 'source_dir'
destination_folder = 'dest_dir'
# Loop through files in source directory
for file in os.listdir(source_folder):
if file.endswith('.txt'):
source_path = os.path.join(source_folder, file)
destination_path = os.path.join(destination_folder, file)
shutil.copy(source_path, destination_path)
print(f"Copied: {file}")
print("All .txt files copied successfully!")
Copied: file1.txt Copied: file2.txt All .txt files copied successfully!
Filtering Files by Name Pattern
To copy files containing specific keywords in their names ?
import os
import shutil
# Create sample files
os.makedirs('source_dir2', exist_ok=True)
os.makedirs('dest_dir2', exist_ok=True)
with open('source_dir2/monthly_report.txt', 'w') as f:
f.write('Monthly report data')
with open('source_dir2/annual_report.pdf', 'w') as f:
f.write('Annual report data')
with open('source_dir2/notes.txt', 'w') as f:
f.write('Regular notes')
source_folder = 'source_dir2'
destination_folder = 'dest_dir2'
keyword = 'report'
for file in os.listdir(source_folder):
if keyword in file:
source_path = os.path.join(source_folder, file)
destination_path = os.path.join(destination_folder, file)
shutil.copy(source_path, destination_path)
print(f"Copied: {file}")
print("All files containing 'report' copied successfully!")
Copied: monthly_report.txt Copied: annual_report.pdf All files containing 'report' copied successfully!
Using pathlib and shutil Modules
The pathlib module provides an object-oriented interface for filesystem paths, making code more readable and cross-platform compatible.
Example with pathlib
Here's how to use Path objects to copy specific files ?
from pathlib import Path
import shutil
# Create sample structure
source_folder = Path('source_dir3')
destination_folder = Path('dest_dir3')
source_folder.mkdir(exist_ok=True)
destination_folder.mkdir(parents=True, exist_ok=True)
# Create sample files
(source_folder / 'document1.txt').write_text('Document 1 content')
(source_folder / 'document2.txt').write_text('Document 2 content')
(source_folder / 'image.jpg').write_text('Image file')
# Copy all .txt files using glob pattern
for file_path in source_folder.glob('*.txt'):
shutil.copy(file_path, destination_folder / file_path.name)
print(f"Copied: {file_path.name}")
print("All .txt files copied using pathlib!")
Copied: document1.txt Copied: document2.txt All .txt files copied using pathlib!
Comparison of Methods
| Method | Best For | Advantages |
|---|---|---|
os + shutil |
Simple file operations | Built-in, widely supported |
pathlib + shutil |
Modern Python code | Object-oriented, readable syntax |
glob patterns |
Complex file matching | Powerful pattern matching |
Conclusion
Use os.listdir() with shutil.copy() for simple file copying tasks. For modern Python code, prefer pathlib with its glob() method for cleaner, more readable file operations.
