Python Glossary Русский

all Python 3tarfileterm

tarfile.TarInfo

tar archives

Describes a single tar member: name, size, type (file, directory, link), permissions, owner and time.

Syntax

info = tarfile.TarInfo(name=''); info.size = len(data)

With addfile(), a TarInfo puts in-memory data into an archive, but you must set size yourself: it defaults to 0, and not a single byte is read from the BytesIO. The name in a TarInfo is what lands on disk on extraction, and it may be '../x' or '/etc/x': before extracting an untrusted archive, check name, type and linkname — or leave that to a filter.

Examples

import io, tarfile
data = 'привет'.encode('utf-8')
with tarfile.open('mem.tar', 'w') as tar:
    empty = tarfile.TarInfo('empty.txt')
    tar.addfile(empty, io.BytesIO(data))
    full = tarfile.TarInfo('full.txt')
    full.size = len(data)
    tar.addfile(full, io.BytesIO(data))
with tarfile.open('mem.tar') as tar:
    for m in tar.getmembers():
        print(m.name, m.size, m.isfile())
# → empty.txt 0 True / full.txt 12 True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy