shutil.copy, shutil.copy2
shutil.copy(src, dst, *, follow_symlinks=True)
shutil.copy2(src, dst, *, follow_symlinks=True)Copy file data, and optionally metadata, returning the destination path.
| Parameter | Description |
|---|---|
src, dst | Source path and destination path or directory. The example uses files inside one TemporaryDirectory. |
follow_symlinks | If True (the default), a symlink source is followed. The example does not use symlinks. |
Returns: The destination path. The example prints only the basename.
Raises
shutil.SameFileError— Raised when src and dst refer to the same file. Measured on Python 3.13.12.
- copy is documented as copying data and mode bits. copy2 is documented as copying data and metadata. The mtime result was measured on this macOS Python 3.13.12 interpreter.
import os
import shutil
import tempfile
with tempfile.TemporaryDirectory(prefix="shutil-ref-") as base:
src = os.path.join(base, "src.txt")
with open(src, "w", encoding="utf-8") as file:
file.write("payload")
os.chmod(src, 0o640)
os.utime(src, (1_700_000_000, 1_700_000_000))
copied = shutil.copy(src, os.path.join(base, "copy.txt"))
copied2 = shutil.copy2(src, os.path.join(base, "copy2.txt"))
def mode_and_mtime(path):
stat = os.stat(path)
return stat.st_mode & 0o777, int(stat.st_mtime)
src_mode, src_mtime = mode_and_mtime(src)
copy_mode, copy_mtime = mode_and_mtime(copied)
copy2_mode, copy2_mtime = mode_and_mtime(copied2)
print("src-mode", oct(src_mode))
print("copy-mode-eq", copy_mode == src_mode)
print("copy2-mode-eq", copy2_mode == src_mode)
print("copy-mtime-eq", copy_mtime == src_mtime)
print("copy2-mtime-eq", copy2_mtime == src_mtime)
print("copy-name", os.path.basename(copied))
print("copy2-name", os.path.basename(copied2))
with open(copied, encoding="utf-8") as file:
print("copy-content", file.read())
try:
shutil.copy(src, src)
except shutil.SameFileError as exc:
print(type(exc).__name__)
Expected output
src-mode 0o640
copy-mode-eq True
copy2-mode-eq True
copy-mtime-eq False
copy2-mtime-eq True
copy-name copy.txt
copy2-name copy2.txt
copy-content payload
SameFileError