How to Copy Files in Python

Python has multiple ways to copy files between directories using built-in modules like shutil and os. These methods work across different Operating System.

Summarize with AI

Not enough time? get the key points instantly.

You can copy files in python using the shutil module which provides high level file and collection of files operations. You can also combine it with os for more control over paths. 

Below are the most common methods:

Method 1: Using shutil.copy()

Copy a file to another location preserving the content but not metadata

python

import shutilshutil.copy(“source.txt”, “destination.txt”)

Use when you just need a quick copy and don’t care about original file metadata. 

Method 2: Using shutil.copy2() for Metadata

Like copy(), but preserve file metadata (timestamps, permissions etc.)

python

import shutilshutil.copy2(“source.txt”, “destination.txt”)

For backups or when file metadata matters. 

Also Read: Python Developer Hourly Rate

Method 3: Copy File to Directory

Copy a file into a directory by providing the destination folder path

python

import shutilshutil.copy(“source.txt”, “/path/to/folder/”)

Python will put the copied file in the target folder with the original filename. 

Method 4: Use os with shutil for Dynamic Paths

Useful when building paths programmatically before copying

python

import osimport shutil

 

src = “source.txt”

dst = os.path.join(“backup”, src)

shutil.copy2(src, dst)

Combines dynamic path handling with safe file copy. 

Also Read:

Tip

  • Always check if the destination path exists before copying to avoid overwriting.
  • For directories use shutil.copytree() to copy entire folders.
  • pathlib can also be used with Path.write_text() or Path.write_bytes() for custom logic.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

Python

OpenCV Kalman Filter with Python

The Kalman Filter is an efficient recursive algorithm used to estimate the state of a system from noisy measurements. In computer vision, it’s commonly used…