Question
How can I copy a file in Python?
For example, I want to take an existing file and create a copy of it at another location or with a different filename. What is the standard way to do this in Python?
Short Answer
By the end of this page, you will understand how file copying works in Python, when to use shutil.copy() or shutil.copy2(), how to copy file contents manually, and what common mistakes to avoid when working with source and destination paths.
Concept
In Python, the most common way to copy a file is to use the shutil module, which is part of the standard library.
File copying means:
- reading data from a source file
- writing that data to a destination file
- optionally preserving metadata such as timestamps or permissions
The shutil module matters because it gives you built-in, reliable tools for common file operations instead of making you manually read and write bytes every time.
The main functions beginners should know are:
shutil.copy(src, dst)— copies file content and basic permissionsshutil.copy2(src, dst)— copies file content and tries to preserve more metadatashutil.copyfile(src, dst)— copies only the file data
In real programming, this is useful for:
- making backups
- duplicating uploaded files
- moving data through processing pipelines
- creating template-based files
- exporting reports or logs
If you want the standard answer to “How do I copy a file in Python?”, shutil.copy() is usually the best starting point.
Mental Model
Think of copying a file like photocopying a document.
- The source file is the original paper.
- The destination file is the new copy.
shutil.copyfile()copies just the words on the page.shutil.copy()copies the words and some basic labels.shutil.copy2()tries to copy the words plus extra details like timestamps.
So the question is not only “Can I make a copy?” but also “How much information should be preserved?”
Syntax and Examples
Basic syntax
import shutil
shutil.copy(source_path, destination_path)
Simplest example
import shutil
shutil.copy("report.txt", "report_backup.txt")
This creates a new file called report_backup.txt with the same contents as report.txt.
Copy to another folder
import shutil
shutil.copy("report.txt", "backups/report.txt")
If backups exists, the file will be copied there.
Preserve more metadata
import shutil
shutil.copy2("report.txt", "backups/report.txt")
Use copy2() when you want to preserve more file information, such as modification times, when possible.
Copy only file contents
import shutil
shutil.copyfile(, )
Step by Step Execution
Example
import shutil
source = "notes.txt"
destination = "notes_copy.txt"
shutil.copy(source, destination)
print("File copied")
What happens step by step
-
import shutil- Python loads the standard library module for high-level file operations.
-
source = "notes.txt"- A variable stores the path of the original file.
-
destination = "notes_copy.txt"- A variable stores the path where the new copy will be created.
-
shutil.copy(source, destination)- Python opens
notes.txt - reads its contents
- creates or overwrites
notes_copy.txt - writes the contents there
- copies basic file permission information as well
- Python opens
-
print("File copied")- If no exception occurred, the message is printed.
Real World Use Cases
Backups
A script may copy a configuration file before editing it:
import shutil
shutil.copy("app.conf", "app.conf.bak")
Report generation
A system may duplicate a template file before filling it with user-specific data.
Log archiving
Applications often copy log files into dated archive folders before rotating them.
Data pipelines
A processing script may copy incoming files into a processed/ directory after validation.
User uploads
A web app may copy uploaded files from a temporary folder into permanent storage.
Testing
Automated tests often copy sample files into a temporary directory so the originals are not modified.
Real Codebase Usage
In real projects, developers usually do more than call copy() once. They combine file copying with validation, error handling, and clear path management.
Common patterns
Validate the source first
from pathlib import Path
import shutil
source = Path("data.csv")
destination = Path("backup/data.csv")
if not source.exists():
raise FileNotFoundError(f"Missing file: {source}")
shutil.copy(source, destination)
This avoids confusing failures later.
Use guard clauses
from pathlib import Path
import shutil
source = Path("image.png")
destination = Path("archive/image.png")
if source == destination:
raise ValueError("Source and destination must be different")
shutil.copy(source, destination)
Create destination folders first
from pathlib import Path
import shutil
source = Path("report.pdf")
destination = Path()
destination.parent.mkdir(parents=, exist_ok=)
shutil.copy(source, destination)
Common Mistakes
1. Forgetting to import shutil
Broken code:
copy("a.txt", "b.txt")
Why it fails:
copyis not available by default
Correct version:
import shutil
shutil.copy("a.txt", "b.txt")
2. Using a destination folder that does not exist
Broken code:
import shutil
shutil.copy("a.txt", "missing_folder/b.txt")
Why it fails:
- Python cannot write into a folder that is not there
Fix:
from pathlib import Path
import shutil
Path("missing_folder").mkdir(exist_ok=True)
shutil.copy("a.txt", "missing_folder/b.txt")
3. Confusing copy with move
Comparisons
Copy function comparison
| Function | Copies file data | Copies permissions | Preserves more metadata | Typical use |
|---|---|---|---|---|
shutil.copyfile() | Yes | No | No | Only file contents matter |
shutil.copy() | Yes | Yes | No | General-purpose file copying |
shutil.copy2() | Yes | Yes | Yes | Backups or archival tasks |
shutil.move() | Not a copy | N/A | N/A |
Cheat Sheet
Quick reference
import shutil
shutil.copy(src, dst) # copy data + basic permissions
shutil.copy2(src, dst) # copy data + more metadata
shutil.copyfile(src, dst) # copy data only
Common examples
shutil.copy("a.txt", "b.txt")
shutil.copy("a.txt", "backup/a.txt")
shutil.copy2("report.txt", "archive/report.txt")
With pathlib
from pathlib import Path
import shutil
src = Path("a.txt")
dst = Path("backup") / "a.txt"
shutil.copy(src, dst)
Rules to remember
- Import
shutilfirst - Source file must exist
- Destination folder must exist unless you create it
copy()does not remove the originalmove()is different fromcopy()- Use
copy2()if metadata matters
FAQ
What is the standard way to copy a file in Python?
Use shutil.copy() for most cases. It is part of Python’s standard library and is the usual high-level solution.
What is the difference between copy() and copy2() in Python?
copy() copies file contents and basic permissions. copy2() also tries to preserve more metadata, such as modification times.
How do I copy a file to another directory in Python?
Pass the destination path including the folder:
shutil.copy("data.txt", "backup/data.txt")
Make sure the destination folder already exists.
Does shutil.copy() overwrite existing files?
Yes, if the destination filename already exists, it will usually be overwritten.
How do I copy a binary file in Python?
Use shutil.copy() or shutil.copyfile(). If copying manually, open files in binary mode with rb and wb.
Can I copy a file without using shutil?
Mini Project
Description
Build a small Python backup script that copies a file into a backup folder. This demonstrates the most common real-world use of file copying: creating a safe duplicate before editing, moving, or processing a file.
Goal
Create a script that copies a chosen file into a backups directory and reports success or failure clearly.
Requirements
- Accept a source file path stored in a variable.
- Create a
backupsfolder if it does not already exist. - Copy the file into that folder using a standard library tool.
- Print a success message showing the destination path.
- Handle the case where the source file does not exist.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Catch Multiple Exceptions in One except Block in Python
Learn how to catch multiple exceptions in one Python except block using tuples, with examples, mistakes, and real-world usage.
Convert Bytes to String in Python 3
Learn how to convert bytes to str in Python 3 using decode(), text mode, and proper encodings with practical examples.