ZetCode

Python copy files

last modified November 29, 2026 Python 3.15

In this article we show how to copy files in Python.

Copying a file means reading its bytes and writing them to a new file. The standard library offers several functions that do this for us. They differ in what they copy besides the data, such as permission bits and timestamps, and in what they accept as the destination. The shutil module provides the classic functions, and since Python 3.14 pathlib.Path has its own copy method.

The examples work with a small text file notes.txt, which has three lines, and they are run in the order of the article: later examples use files created by earlier ones.

Copying with open

The basic way to copy a file uses only the built-in open function. We read the source in binary mode and write the bytes to the destination.

copy_bytes.py
with open('notes.txt', 'rb') as src:
    data = src.read()

with open('notes_copy.txt', 'wb') as dst:
    dst.write(data)

print(len(data), 'bytes copied')

with open('notes_copy.txt') as f:
    print(f.read(), end='')

Binary mode, 'rb' and 'wb', copies the bytes exactly as they are, without decoding text or translating line endings. This works for any kind of file: text, images, or archives. The read call loads the whole file into memory, which is fine for small files.

$ python copy_bytes.py
70 bytes copied
Buy milk and bread.
Call the dentist on Monday.
Return library books.

Copying in chunks

A large file should not be loaded into memory at once. Instead, we read and write it in chunks of fixed size.

copy_chunks.py
import os
import filecmp

with open('data.bin', 'wb') as f:
    f.write(os.urandom(1_000_000))

CHUNK = 64 * 1024

with open('data.bin', 'rb') as src, open('data_copy.bin', 'wb') as dst:
    while chunk := src.read(CHUNK):
        dst.write(chunk)

print(os.path.getsize('data_copy.bin'))
print(filecmp.cmp('data.bin', 'data_copy.bin', shallow=False))

The program first creates a one-megabyte file of random bytes. The loop reads 64 KiB at a time; the walrus operator assigns the chunk and ends the loop when read returns an empty bytes object at the end of the file. Memory use stays at one chunk regardless of the file size. The filecmp.cmp function with shallow=False compares the contents of the two files byte by byte.

$ python copy_chunks.py
1000000
True

shutil.copyfile

The shutil.copyfile function copies the contents of a file to a destination file name. It does the chunked loop for us and uses fast operating system calls where they are available.

shutil_copyfile.py
import shutil

dest = shutil.copyfile('notes.txt', 'notes_backup.txt')
print(dest)

with open('notes_backup.txt', 'w') as f:
    f.write('old backup\n')

shutil.copyfile('notes.txt', 'notes_backup.txt')

with open('notes_backup.txt') as f:
    print(f.readline(), end='')

The function returns the destination path. If the destination exists, it is overwritten without a warning: the old backup is replaced by the new copy. Only the data is copied; the new file gets default permissions and the current time as its modification time.

$ python shutil_copyfile.py
notes_backup.txt
Buy milk and bread.

shutil.copy and permissions

The shutil.copy function copies the data and the permission bits. The destination can also be a directory; the file then keeps its name.

permissions.py
import os
import shutil
import stat

os.chmod('deploy.sh', 0o755)
os.makedirs('backup', exist_ok=True)

shutil.copyfile('deploy.sh', 'deploy_data.sh')
dest = shutil.copy('deploy.sh', 'backup')

for name in ['deploy.sh', 'deploy_data.sh', dest]:
    mode = os.stat(name).st_mode
    print(stat.filemode(mode), name)

We make deploy.sh executable and copy it twice. The copy made by copyfile has the default mode, which depends on the umask of the user, so the script is no longer executable. shutil.copy keeps the x bits. Given the directory backup, it creates backup/deploy.sh and returns that path.

$ python permissions.py
-rwxr-xr-x deploy.sh
-rw-rw-r-- deploy_data.sh
-rwxr-xr-x backup/deploy.sh

shutil.copy2 and timestamps

The shutil.copy2 function works like copy, but also copies the access and modification times and, where possible, other metadata such as extended attributes.

metadata.py
import os
import shutil
from datetime import datetime

stamp = datetime(2025, 3, 31, 9, 30).timestamp()
os.utime('notes.txt', (stamp, stamp))

shutil.copy('notes.txt', 'notes_copy.txt')
shutil.copy2('notes.txt', 'notes_copy2.txt')

for name in ['notes.txt', 'notes_copy.txt', 'notes_copy2.txt']:
    mtime = os.path.getmtime(name)
    same = mtime == stamp
    print(f'{name:16} {datetime.fromtimestamp(mtime):%Y-%m-%d %H:%M} {same}')

We set the modification time of notes.txt to a fixed date with os.utime. The copy made by shutil.copy has the time when the program ran, while copy2 keeps the original date. Backup tools need copy2, because a changed timestamp makes a file look new. Neither function copies the owner of the file or the creation time on all platforms.

$ python metadata.py
notes.txt        2025-03-31 09:30 True
notes_copy.txt   2026-11-29 17:33 False
notes_copy2.txt  2025-03-31 09:30 True

Copy errors

The copy functions raise OSError subclasses when a file is missing, cannot be read, or the destination cannot be written. Copying a file onto itself raises shutil.SameFileError.

errors.py
import shutil

cases = [
    ('missing.txt', 'out.txt'),
    ('notes.txt', 'notes.txt'),
    ('notes.txt', 'backup'),
]

for src, dst in cases:
    try:
        shutil.copyfile(src, dst)
    except shutil.SameFileError as e:
        print('same file:', e)
    except OSError as e:
        print(type(e).__name__ + ':', e.strerror, e.filename)

A missing source gives FileNotFoundError. Copying a file to its own path would truncate it before reading, so shutil refuses with SameFileError, which is also an OSError; that is why it is caught first. Unlike copy, copyfile does not accept a directory as the destination. The exact messages depend on the operating system.

$ python errors.py
FileNotFoundError: No such file or directory missing.txt
same file: 'notes.txt' and 'notes.txt' are the same file
IsADirectoryError: Is a directory backup

Not overwriting files

To avoid overwriting, we can check whether the destination exists before copying. A safer way is to open the destination in the exclusive creation mode 'x', which fails if the file exists.

no_overwrite.py
import shutil


def copy_new(src, dst):
    with open(src, 'rb') as fsrc, open(dst, 'xb') as fdst:
        shutil.copyfileobj(fsrc, fdst)


for dst in ['report.txt', 'report.txt']:
    try:
        copy_new('notes.txt', dst)
        print('created', dst)
    except FileExistsError:
        print(dst, 'already exists, not overwritten')

The shutil.copyfileobj function copies data between two open file objects. The first call creates report.txt; the second raises FileExistsError and leaves the file untouched. A separate existence check followed by a copy leaves a short time in which another process can create the file; the 'x' mode makes the check and the creation a single operation.

$ python no_overwrite.py
created report.txt
report.txt already exists, not overwritten

Copying between file objects

Since copyfileobj works with file objects, it can copy data to and from anything that has read and write methods: compressed files, in-memory buffers, or network streams.

file_objects.py
import gzip
import io
import os
import shutil

with open('notes.txt', 'rb') as src, gzip.open('notes.txt.gz', 'wb') as dst:
    shutil.copyfileobj(src, dst)

print(os.path.getsize('notes.txt'), os.path.getsize('notes.txt.gz'))

buffer = io.BytesIO()
with gzip.open('notes.txt.gz', 'rb') as src:
    shutil.copyfileobj(src, buffer)

print(buffer.getvalue().decode().splitlines()[0])

The first block copies notes.txt into a gzip-compressed file; the gzip object compresses the data as it is written. For such a short file, the gzip header makes the result larger than the original. The second block decompresses the file into an io.BytesIO buffer in memory. The optional third argument of copyfileobj sets the chunk size.

$ python file_objects.py
70 96
Buy milk and bread.

Showing progress

The shutil functions have no progress callback. To report progress, we write the chunked loop ourselves and count the copied bytes.

progress.py
import os


def copy_with_progress(src, dst, chunk_size=256 * 1024):
    total = os.path.getsize(src)
    done = 0
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
        while chunk := fsrc.read(chunk_size):
            fdst.write(chunk)
            done += len(chunk)
            print(f'{done:>9,} / {total:,} bytes {done / total:6.1%}')


copy_with_progress('data.bin', 'data_backup.bin')

The function gets the size of the source first and prints a line after each 256 KiB chunk. The :, format adds thousands separators, and .1% turns the ratio into a percentage. A real program would update a single line or a progress bar instead of printing many lines.

$ python progress.py
  262,144 / 1,000,000 bytes  26.2%
  524,288 / 1,000,000 bytes  52.4%
  786,432 / 1,000,000 bytes  78.6%
1,000,000 / 1,000,000 bytes 100.0%

Path.copy

Python 3.14 added the copy and copy_into methods to pathlib.Path. They return a Path object for the new file.

path_copy.py
from pathlib import Path
import stat

src = Path('deploy.sh')

dest = src.copy('deploy_v2.sh')
print(dest, stat.filemode(dest.stat().st_mode))

dest = src.copy('deploy_v3.sh', preserve_metadata=True)
print(dest, stat.filemode(dest.stat().st_mode))
print(dest.stat().st_mtime == src.stat().st_mtime)

Path('archive').mkdir(exist_ok=True)
dest = Path('notes.txt').copy_into('archive')
print(dest)

By default, copy guarantees only the data, like shutil.copyfile: the copy of the executable script has the default mode. With preserve_metadata=True, it also copies the permission bits and timestamps, like copy2. The copy_into method takes a destination directory and keeps the file name. Both methods also copy whole directories when called on a directory path. The Python pathlib article covers the module in more detail.

$ python path_copy.py
deploy_v2.sh -rw-rw-r--
deploy_v3.sh -rwxr-xr-x
True
archive/notes.txt

Copying a directory tree

The shutil.copytree function copies a directory with all its files and subdirectories. Files are copied with copy2, so they keep their timestamps.

copy_tree.py
import os
import shutil

ignore = shutil.ignore_patterns('*.tmp', '__pycache__')
shutil.copytree('project', 'project_backup', ignore=ignore)

for root, dirs, files in os.walk('project_backup'):
    dirs.sort()
    for name in sorted(files):
        print(os.path.join(root, name))

shutil.copytree('project', 'project_backup', ignore=ignore,
                dirs_exist_ok=True)
print('updated')

The ignore_patterns helper builds a filter from shell-style patterns; the temporary file and the __pycache__ directory are skipped. By default, copytree fails if the destination exists. With dirs_exist_ok=True, it copies into the existing directory and overwrites files with the same name, which is how the second call updates the backup. Moving, deleting, and archiving directories are covered in Python shutil.

$ python copy_tree.py
project_backup/main.py
project_backup/util.py
project_backup/docs/guide.txt
updated

Source

shutil – High-level file operations, pathlib – Copying, moving and deleting, open function, filecmp – File and directory comparisons

In this article we have copied files with open, in chunks, and with the shutil copyfile, copy, copy2, and copyfileobj functions, handled copy errors, avoided overwriting, reported progress, used Path.copy, and copied directory trees. See also Python open function, Python shutil, and Python pathlib.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.