Python Glossary Русский

all Python 3shutilfunction

shutil.copyfile()

copying files

Copies only the contents of the file at src to the file dst — without permissions, modification time or other metadata.

Syntax

shutil.copyfile(src, dst, *, follow_symlinks=True) -> dst

The barest of the copy functions: copyfile copies only data, copymode only the permission bits, copystat permissions and times without data, copy = copyfile + copymode, copy2 = copyfile + copystat. dst must be a file path: a directory there raises IsADirectoryError (PermissionError on Windows), whereas copy() and copy2() would put the file inside it. An existing dst is silently overwritten, and copying a file onto itself raises SameFileError.

Examples

import os, shutil
with open('a.txt', 'w') as f:
    f.write('data')
os.chmod('a.txt', 0o600)
print(shutil.copyfile('a.txt', 'b.txt'))  # → b.txt
print(open('b.txt').read())  # → data
print(oct(os.stat('b.txt').st_mode & 0o777))  # → ? 0o644 — права по umask, не 0o600
import os, shutil
os.mkdir('folder')
open('a.txt', 'w').close()
try:
    shutil.copyfile('a.txt', 'folder')
except IsADirectoryError as e:
    print(type(e).__name__)  # → IsADirectoryError
try:
    shutil.copyfile('a.txt', 'a.txt')
except shutil.SameFileError as e:
    print(e)  # → 'a.txt' and 'a.txt' are the same file

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy