Python Glossary Русский

all Python 3shutilfunction

shutil.copyfileobj()

copying files

Copies data from one open file object to another in chunks — without loading the whole file into memory.

Syntax

shutil.copyfileobj(fsrc, fdst[, length])

It works on objects, not paths: opening the files (both binary or both text) and closing them is your job. Copying starts at the source's current position: if the file was already read, or data was just written into a BytesIO, nothing gets copied — call seek(0) first. Permissions, modification time and other metadata are never transferred: an object has none.

Examples

import io, shutil
src = io.BytesIO()
src.write(b'hello')
dst = io.BytesIO()
shutil.copyfileobj(src, dst)
print(dst.getvalue())  # → b'' — позиция src стояла в конце
src.seek(0)
shutil.copyfileobj(src, dst)
print(dst.getvalue())  # → b'hello'
import shutil
with open('a.txt', 'w', encoding='utf-8') as f:
    f.write('строка\n' * 3)
with open('a.txt', 'rb') as fsrc, open('b.txt', 'wb') as fdst:
    shutil.copyfileobj(fsrc, fdst, length=1024)
print(open('b.txt', encoding='utf-8').read().count('строка'))  # → 3

See also

Open in the full glossarydocs.python.orgReport an inaccuracy