Question

How to Copy a File in Python

pythonfilecopyfilesystemsfile-copying

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 permissions
  • shutil.copy2(src, dst) — copies file content and tries to preserve more metadata
  • shutil.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?”

Take Quiz

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("report.txt", "copy.txt")

Use copyfile() when you only care about the data inside the file.

Manual copy using file objects

with open("report.txt", "rb") as src, open("copy.txt", "wb") as dst:
    dst.write(src.read())

This works, but for normal file copying, shutil.copy() is usually cleaner and safer.

Using pathlib

from pathlib import Path
import shutil

source = Path("report.txt")
destination = Path("backups") / "report.txt"

shutil.copy(source, destination)

pathlib makes path handling more readable, especially in larger programs.

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

  1. import shutil

    • Python loads the standard library module for high-level file operations.
  2. source = "notes.txt"

    • A variable stores the path of the original file.
  3. destination = "notes_copy.txt"

    • A variable stores the path where the new copy will be created.
  4. 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
  5. print("File copied")

    • If no exception occurred, the message is printed.

Small trace example

Suppose notes.txt contains:

Buy milk
Call Alex

After the copy:

  • notes.txt still exists unchanged
  • notes_copy.txt now also contains:
Buy milk
Call Alex

Both files now have the same contents, but they are separate files.

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.

Take Quiz

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("exports/2026/report.pdf")

destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(source, destination)

Handle errors explicitly

import shutil

try:
    shutil.copy("report.txt", "backup/report.txt")
except FileNotFoundError:
    print("The source file does not exist.")
except PermissionError:
    print("Permission denied.")

Use temporary copies in workflows

Developers often copy a file before transforming it so the original remains untouched. This is common in ETL scripts, image processing tools, and deployment systems.

Common Mistakes

1. Forgetting to import shutil

Broken code:

copy("a.txt", "b.txt")

Why it fails:

  • copy is 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

  • shutil.copy() leaves the original file in place
  • shutil.move() relocates it

If you want both files to exist, use copy, not move.

4. Copying text files manually in text mode when binary mode is safer

Problematic approach:

with open("photo.jpg", "r") as src, open("photo_copy.jpg", "w") as dst:
    dst.write(src.read())

Why it is wrong:

  • binary files should not be read with "r" and written with "w"

Correct version:

with open("photo.jpg", "rb") as src, open("photo_copy.jpg", "wb") as dst:
    dst.write(src.read())

5. Assuming metadata is always preserved

  • copyfile() copies data only
  • copy() copies data and basic permission bits
  • copy2() tries to preserve more metadata

Choose the right function for your needs.

6. Copying a file onto itself

Broken example:

import shutil

shutil.copy("data.txt", "data.txt")

This raises an error because the source and destination are the same file.

Comparisons

Copy function comparison

FunctionCopies file dataCopies permissionsPreserves more metadataTypical use
shutil.copyfile()YesNoNoOnly file contents matter
shutil.copy()YesYesNoGeneral-purpose file copying
shutil.copy2()YesYesYesBackups or archival tasks
shutil.move()Not a copyN/AN/AMove or rename a file

shutil.copy() vs manual read/write

ApproachBest forProsCons
shutil.copy()Normal file copyingSimple, readable, standardLess control over low-level behavior
Manual open() and read()Learning or custom processingFull controlMore code, easier to make mistakes

str paths vs pathlib.Path

OptionExampleBenefit
String path"backup/file.txt"Simple for small scripts
Path objectPath("backup") / "file.txt"Cleaner and easier in larger codebases
Take Quiz

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 shutil first
  • Source file must exist
  • Destination folder must exist unless you create it
  • copy() does not remove the original
  • move() is different from copy()
  • Use copy2() if metadata matters
  • Use binary mode (rb, wb) for manual copying of binary files

Helpful pattern

from pathlib import Path
import shutil

src = Path("report.txt")
dst = Path("backup/report.txt")
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy(src, dst)

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?

Yes, by opening the source and destination files and writing the contents manually. But shutil is simpler for normal copying.

What happens if the source file does not exist?

Python raises a FileNotFoundError.

Should I use os or shutil to copy files in Python?

Use shutil for copying files. The os module is more about path and operating system interactions.

Take Quiz

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 backups folder 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.
Take Quiz

Keep learning

Related questions

View more