all Python 3tarfilefunction
tarfile.open()
tar archives
Opens a tar archive for reading or writing and returns a TarFile; the mode sets compression: 'w:gz', 'r:*', 'r|gz'.
Syntax
tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)
When reading, 'r' detects compression by itself, but 'w' writes an uncompressed .tar — even if the name ends in .tar.gz; ask for compression explicitly: 'w:gz', 'w:bz2', 'w:xz'. Extracting someone else's archive without a filter is dangerous: a name like '../x' or a link pointing outside writes past the target folder. Before 3.14 extractall() trusted the archive completely by default (with a DeprecationWarning on 3.12–3.13), so pass filter='data' explicitly.
Examples
import tarfile
with open('report.txt', 'w', encoding='utf-8') as f:
f.write('итоги')
with tarfile.open('backup.tar.gz', 'w:gz') as tar:
tar.add('report.txt')
with tarfile.open('backup.tar.gz') as tar:
print(tar.getnames()) # → ['report.txt']
tar.extractall('restored', filter='data')
with open('restored/report.txt', encoding='utf-8') as f:
print(f.read()) # → итоги
import tarfile
with open('a.txt', 'w', encoding='utf-8') as f:
f.write('x' * 1000)
with tarfile.open('plain.tar.gz', 'w') as tar:
tar.add('a.txt')
try:
tarfile.open('plain.tar.gz', 'r:gz')
except tarfile.ReadError as e:
print(e) # → not a gzip file — режим 'w' не сжимал
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy