tarfile - Read from and write to tar format archives.
| Use Case | Command | Description |
|---|---|---|
| π¦ Open tar for reading | tarfile.open("archive.tar") | Open with transparent compression detection |
| π¦ Open tar for writing | tarfile.open("archive.tar", "w") | Create a new uncompressed tar (overwrites) |
| π¦ Open tar for appending | tarfile.open("archive.tar", "a") | Append to an existing archive |
| ποΈ Open compressed tar | tarfile.open("archive.tar.gz", "r:gz") | Read gzip-compressed tar |
| π List members | tar.getmembers() | Returns list of TarInfo objects |
| π List names | tar.getnames() | Returns list of member names |
| π Extract single file | tar.extract("file.txt") | Extract to current directory |
| π Extract all files | tar.extractall() | Extract entire archive |
| β Add file | tar.add("myfile") | Add a file or directory recursively |
| π Check if tar | tarfile.is_tarfile("archive") | Returns True if it's a valid tar |
https://docs.python.org/3.10/library/tarfile.html
The following documentation is automatically generated from the Python source files. It may be incomplete, incorrect or include features that are considered implementation detail and may vary between Python implementations. When in doubt, consult the module reference at the location listed above.
builtins.Exception(builtins.BaseException)
TarError
CompressionError
ExtractError
HeaderError
ReadError
StreamError
builtins.object
TarFile
TarInfo
Exception for unavailable compression methods.
Inherits from TarError β builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors inherited from TarError:
__weakref__ - list of weak references to the object (if defined)Standard exception methods (__init__, __new__, __repr__, __str__, etc.) inherited from builtins.Exception and builtins.BaseException.
General exception for extract errors.
Inherits from TarError β builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors inherited from TarError:
__weakref__ - list of weak references to the object (if defined)Standard exception methods inherited.
Base exception for header errors.
Inherits from TarError β builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors inherited from TarError:
__weakref__ - list of weak references to the object (if defined)Standard exception methods inherited.
Exception for unreadable tar archives.
Inherits from TarError β builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors inherited from TarError:
__weakref__ - list of weak references to the object (if defined)Standard exception methods inherited.
Exception for unsupported operations on stream-like TarFiles.
Inherits from TarError β builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors inherited from TarError:
__weakref__ - list of weak references to the object (if defined)Standard exception methods inherited.
Base exception.
Inherits from builtins.Exception β builtins.BaseException β builtins.object.
Data descriptors defined here:
__weakref__ - list of weak references to the object (if defined)Standard exception methods inherited.
TarFile(name=None, mode='r', fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors='surrogateescape', pax_headers=None, debug=None, errorlevel=None, copybufsize=None)
The TarFile Class provides an interface to tar archives.
__enter__(self)__exit__(self, type, value, traceback)__init__(self, name=None, mode='r', fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors='surrogateescape', pax_headers=None, debug=None, errorlevel=None, copybufsize=None)name. mode is either 'r' to read, 'a' to append, or 'w' to write. mode defaults to 'r'. If fileobj is given, it is used for reading/writing and overrides mode if determinable. fileobj is not closed when TarFile is closed.__iter__(self) - Provide an iterator object.add(self, name, arcname=None, recursive=True, *, filter=None)name to the archive. name may be any type of file (directory, fifo, symbolic link, etc.). If given, arcname specifies an alternative name in the archive. Directories are added recursively by default; set recursive to False to avoid. filter is a function that expects a TarInfo object and returns the changed TarInfo or None to exclude it.addfile(self, tarinfo, fileobj=None)tarinfo to the archive. If fileobj is given, it should be a binary file, and tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects directly, or by using gettarinfo().chmod(self, tarinfo, targetpath) - Set file permissions of targetpath according to tarinfo.chown(self, tarinfo, targetpath, numeric_owner) - Set owner of targetpath according to tarinfo. If numeric_owner is True, use .gid/.uid instead of .gname/.uname. If False, fall back to .gid/.uid when the name search fails.close(self) - Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive.extract(self, member, path='', set_attrs=True, *, numeric_owner=False, filter=None)member may be a filename or a TarInfo object. path specifies a different directory. File attributes (owner, mtime, mode) are set unless set_attrs is False. If numeric_owner is True, only the numbers for user/group names are used. The filter function will be called before extraction; it can return a changed TarInfo or None to skip the member. String names of common filters are accepted.extractall(self, path='.', members=None, *, numeric_owner=False, filter=None)path specifies a different directory. members is optional and must be a subset of the list returned by getmembers(). If numeric_owner is True, only the numbers for user/group names are used. The filter function will be called on each member just before extraction; it can return a changed TarInfo or None to skip the member. String names of common filters are accepted.extractfile(self, member)member may be a filename or a TarInfo object. If member is a regular file or a link, an io.BufferedReader object is returned. For all other existing members, None is returned. If member does not appear in the archive, KeyError is raised.getmember(self, name)name. If name can not be found in the archive, KeyError is raised. If a member occurs more than once, its last occurrence is assumed to be the most up-to-date version.getmembers(self) - Return the members of the archive as a list of TarInfo objects. The list has the same order as the members in the archive.getnames(self) - Return the members of the archive as a list of their names. Same order as getmembers().gettarinfo(self, name=None, arcname=None, fileobj=None)os.stat or equivalent on an existing file. The file is either named by name, or specified as a file object fileobj with a file descriptor. If given, arcname specifies an alternative name for the file in the archive, otherwise the name is taken from the name attribute of fileobj or the name argument. The name should be a text string.list(self, verbose=True, *, members=None)sys.stdout. If verbose is False, only the names of the members are printed. If True, an ls -l-like output is produced. members is optional and must be a subset of the list returned by getmembers().makedev(self, tarinfo, targetpath) - Make a character or block device called targetpath.makedir(self, tarinfo, targetpath) - Make a directory called targetpath.makefifo(self, tarinfo, targetpath) - Make a fifo called targetpath.makefile(self, tarinfo, targetpath) - Make a file called targetpath.makelink(self, tarinfo, targetpath) - Make a (symbolic) link called targetpath. If it cannot be created (platform limitation), we try to make a copy of the referenced file instead of a link.makeunknown(self, tarinfo, targetpath) - Make a file from a TarInfo object with an unknown type at targetpath.next(self) - Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available.utime(self, tarinfo, targetpath) - Set modification time of targetpath according to tarinfo.bz2open(name, mode='r', fileobj=None, compresslevel=9, **kwargs) - Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed.gzopen(name, mode='r', fileobj=None, compresslevel=9, **kwargs) - Open gzip compressed tar archive name for reading or writing. Appending is not allowed.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) - Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.mode:
'r' or 'r:*' open for reading with transparent compression
'r:' open for reading exclusively uncompressed
'r:gz' open for reading with gzip compression
'r:bz2' open for reading with bzip2 compression
'r:xz' open for reading with lzma compression
'a' or 'a:' open for appending, creating the file if necessary
'w' or 'w:' open for writing without compression
'w:gz' open for writing with gzip compression
'w:bz2' open for writing with bzip2 compression
'w:xz' open for writing with lzma compression
'x' or 'x:' create a tarfile exclusively without compression, raise
an exception if the file is already created
'x:gz' create a gzip compressed tarfile, raise an exception
if the file is already created
'x:bz2' create a bzip2 compressed tarfile, raise an exception
if the file is already created
'x:xz' create an lzma compressed tarfile, raise an exception
if the file is already created
'r|*' open a stream of tar blocks with transparent compression
'r|' open an uncompressed stream of tar blocks for reading
'r|gz' open a gzip compressed stream of tar blocks
'r|bz2' open a bzip2 compressed stream of tar blocks
'r|xz' open an lzma compressed stream of tar blocks
'w|' open an uncompressed stream for writing
'w|gz' open a gzip compressed stream for writing
'w|bz2' open a bzip2 compressed stream for writing
'w|xz' open an lzma compressed stream for writingtaropen(name, mode='r', fileobj=None, **kwargs) - Open uncompressed tar archive name for reading or writing.xzopen(name, mode='r', fileobj=None, preset=None, **kwargs) - Open lzma compressed tar archive name for reading or writing. Appending is not allowed.__dict__ - dictionary for instance variables (if defined)__weakref__ - list of weak references to the object (if defined)OPEN_METH = {'bz2': 'bz2open', 'gz': 'gzopen', 'tar': 'taropen', 'xz':...}
debug = 0dereference = Falseencoding = 'utf-8'errorlevel = 1errors = Noneextraction_filter = Nonefileobject = <class 'tarfile.ExFileObject'>format = 2ignore_zeros = Falsetarinfo = <class 'tarfile.TarInfo'> - Informational class which holds the details about an archive member given by a tar header block. TarInfo objects are returned by TarFile.getmember(), TarFile.getmembers() and TarFile.gettarinfo() and are usually created internally.TarInfo(name='')
Informational class which holds the details about an archive member given by a tar header block. TarInfo objects are returned by TarFile.getmember(), TarFile.getmembers() and TarFile.gettarinfo() and are usually created internally.
__init__(self, name='') - Construct a TarInfo object. name is the optional name of the member.__repr__(self) - Return repr(self).create_gnu_header(self, info, encoding, errors) - Return the object as a GNU header block sequence.create_pax_header(self, info, encoding) - Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information.create_ustar_header(self, info, encoding, errors) - Return the object as a ustar header block.get_info(self) - Return the TarInfo's attributes as a dictionary.isblk(self) - Return True if it is a block device.ischr(self) - Return True if it is a character device.isdev(self) - Return True if it is one of character device, block device or FIFO.isdir(self) - Return True if it is a directory.isfifo(self) - Return True if it is a FIFO.isfile(self) - Return True if the Tarinfo object is a regular file.islnk(self) - Return True if it is a hard link.isreg(self) - Return True if the Tarinfo object is a regular file.issparse(self)issym(self) - Return True if it is a symbolic link.replace(self, *, name=<object object at 0x7f6915ad0af0>, mtime=<object object at 0x7f6915ad0af0>, mode=<object object at 0x7f6915ad0af0>, linkname=<object object at 0x7f6915ad0af0>, uid=<object object at 0x7f6915ad0af0>, gid=<object object at 0x7f6915ad0af0>, uname=<object object at 0x7f6915ad0af0>, gname=<object object at 0x7f6915ad0af0>, deep=True, _KEEP=<object object at 0x7f6915ad0af0>) - Return a deep copy of self with the given attributes replaced.tobuf(self, format=2, encoding='utf-8', errors='surrogateescape') - Return a tar header as a string of 512 byte blocks.create_pax_global_header(pax_headers) - Return the object as a pax global header block sequence.frombuf(buf, encoding, errors) - Construct a TarInfo object from a 512 byte bytes object.fromtarfile(tarfile) - Return the next TarInfo object from TarFile object tarfile.chksum - Header checksum.devmajor - Device major number.devminor - Device minor number.gid - Group ID of the user who originally stored this member.gname - Group name.linkname - Name of the target file name, which is only present in TarInfo objects of type LNKTYPE and SYMTYPE.linkpath - In pax headers, "linkname" is called "linkpath".mode - Permission bits.mtime - Time of last modification.name - Name of the archive member.offset - The tar header starts here.offset_data - The file's data starts here.path - In pax headers, "name" is called "path".pax_headers - A dictionary containing key-value pairs of an associated pax extended header.size - Size in bytes.sparse - Sparse member information.tarfiletype - File type. type is usually one of these constants: REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE, CHRTYPE, BLKTYPE, GNUTYPE_SPARSE.uid - User ID of the user who originally stored this member.uname - User name.is_tarfile(name)Return True if name points to a tar archive that we are able to handle, else return False. name should be a string, file, or file-like object.
open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)Open a tar archive for reading, writing or appending. Return an appropriate TarFile class.
mode:
'r' or 'r:*' open for reading with transparent compression
'r:' open for reading exclusively uncompressed
'r:gz' open for reading with gzip compression
'r:bz2' open for reading with bzip2 compression
'r:xz' open for reading with lzma compression
'a' or 'a:' open for appending, creating the file if necessary
'w' or 'w:' open for writing without compression
'w:gz' open for writing with gzip compression
'w:bz2' open for writing with bzip2 compression
'w:xz' open for writing with lzma compression
'x' or 'x:' create a tarfile exclusively without compression, raise
an exception if the file is already created
'x:gz' create a gzip compressed tarfile, raise an exception
if the file is already created
'x:bz2' create a bzip2 compressed tarfile, raise an exception
if the file is already created
'x:xz' create an lzma compressed tarfile, raise an exception
if the file is already created
'r|*' open a stream of tar blocks with transparent compression
'r|' open an uncompressed stream of tar blocks for reading
'r|gz' open a gzip compressed stream of tar blocks
'r|bz2' open a bzip2 compressed stream of tar blocks
'r|xz' open an lzma compressed stream of tar blocks
'w|' open an uncompressed stream for writing
'w|gz' open a gzip compressed stream for writing
'w|bz2' open a bzip2 compressed stream for writing
'w|xz' open an lzma compressed stream for writing
DEFAULT_FORMAT = 2
ENCODING = 'utf-8'
GNU_FORMAT = 1
PAX_FORMAT = 2
USTAR_FORMAT = 0
__all__ = ['TarFile', 'TarInfo', 'is_tarfile', 'TarError', 'ReadError'...
Lars GustΓ€bel (lars AT gustaebel.de)
Gustavo Niemeyer, Niels GustΓ€bel, Richard Townsend.
/usr/lib/python3.10/tarfile.py
Generated by phpman v4.9.27 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-07-18 11:10 @216.73.216.114
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format