How to copy files in Python?
Copying files is a common task in many Python applications, whether you're managing data, organizing files, or performing backups. Python provides several ways to copy files, primarily through the built-in shutil
module and the newer pathlib
module introduced in Python 3.4. This guide will walk you through various methods to copy files in Python, complete with examples and best practices.
Using the shutil
Module
The shutil
(shell utilities) module offers a higher-level interface for file operations compared to basic file handling in Python. It's the most commonly used module for copying files and directories.
shutil.copy()
Purpose: Copies the content of the source file to the destination. It also attempts to preserve the file's permission mode but not other metadata like timestamps.
Syntax:
shutil.copy(src, dst, *, follow_symlinks=True)
src
: Path to the source file.dst
: Destination path or directory.follow_symlinks
: IfTrue
, andsrc
is a symbolic link, the file pointed to by the symlink is copied.
Example:
import shutil # Copy 'example.txt' to the 'backup' directory shutil.copy('example.txt', 'backup/example.txt') # Copy 'example.txt' into the 'backup' directory, preserving the original filename shutil.copy('example.txt', 'backup/')
Notes:
- If the destination is a directory, the file is copied into that directory with the same filename.
- If the destination is a file path, it will be overwritten if it exists.
shutil.copy2()
Purpose: Similar to shutil.copy()
, but it also attempts to preserve all file metadata, including timestamps and permissions.
Syntax:
shutil.copy2(src, dst, *, follow_symlinks=True)
Example:
import shutil # Copy 'example.txt' to 'backup/example.txt', preserving metadata shutil.copy2('example.txt', 'backup/example.txt')
When to Use: When preserving file metadata is important, such as in backups or when file timestamps are significant.
shutil.copyfile()
Purpose: Copies the contents of the source file to the destination file. Unlike shutil.copy()
and shutil.copy2()
, it does not preserve file permissions or metadata.
Syntax:
shutil.copyfile(src, dst, *, follow_symlinks=True)
Example:
import shutil # Copy 'example.txt' to 'backup/example_copy.txt' shutil.copyfile('example.txt', 'backup/example_copy.txt')
Notes:
- Both
src
anddst
must be file paths. Ifdst
is a directory, aIsADirectoryError
is raised. - Useful when you only need the file content without any metadata.
shutil.copytree()
Purpose: Recursively copies an entire directory tree from the source to the destination.
Syntax:
shutil.copytree(src, dst, symlinks=False, ignore=None, copy_function=shutil.copy2, ignore_dangling_symlinks=False)
src
: Source directory.dst
: Destination directory.symlinks
: IfTrue
, symbolic links in the source tree are represented as symbolic links in the destination.ignore
: A callable that takes a directory name and its contents and returns a list of names to ignore.copy_function
: The function used to copy each file. Defaults toshutil.copy2
.ignore_dangling_symlinks
: IfTrue
, ignores dangling symlinks.
Example:
import shutil # Copy the entire 'data' directory to 'backup/data_copy' shutil.copytree('data', 'backup/data_copy')
Handling Existing Destination:
By default, shutil.copytree()
requires that the destination directory does not already exist. To overwrite or merge with an existing directory, additional handling is required.
Example with dirs_exist_ok
(Python 3.8+):
import shutil # Merge 'data' directory into 'backup/data_copy', allowing existing directories shutil.copytree('data', 'backup/data_copy', dirs_exist_ok=True)
Summary of shutil
Copy Functions
| Function | Copies Metadata | Copies Permissions | Suitable For | |
GET YOUR FREE
Coding Questions Catalog