Python Glossary Русский

all Python 3tarfileterm

tarfile.TarFile

tar archives

An open tar archive object: adding files, listing members, reading and extracting; created via tarfile.open().

Syntax

with tarfile.open(name, mode) as tar: ...

add() on a directory is recursive by default and stores the path as you passed it: tar.add('/home/u/proj') puts the whole path into the archive, and arcname sets the name you want. extractfile() reads a member into memory without touching the disk — a safe way to peek into an untrusted archive. extract() and extractall() without filter trusted the archive completely before 3.14; the extraction_filter attribute sets a filter for the whole object.

Examples

import os, tarfile
os.makedirs('proj/src', exist_ok=True)
with open('proj/src/main.py', 'w', encoding='utf-8') as f:
    f.write('print(1)')
with tarfile.open('p.tar', 'w') as tar:
    tar.add('proj', arcname='app')
with tarfile.open('p.tar') as tar:
    print(tar.getnames())  # → ['app', 'app/src', 'app/src/main.py']
    print(tar.extractfile('app/src/main.py').read())  # → b'print(1)'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy