tarfile β Read from and write to tar format archives.
| Use Case | Command | Description |
|---|---|---|
| π Open tar archive for reading (auto-detect compression) | tarfile.open('archive.tar.gz', 'r') | Opens with transparent compression; returns a TarFile object. |
| π¦ Open tar for writing with gzip compression | tarfile.open('archive.tar.gz', 'w:gz') | Creates a new gzip-compressed tar archive. |
| β Add a file to an archive | tar.add('file.txt') | Adds file.txt to the open TarFile. |
| π€ Extract all members to current directory | tar.extractall() | Extracts all files, preserving metadata. |
| π List contents (table of files) | tar.list() | Prints an ls -l-style listing of archive members. |
| π Check if a file is a tar archive | tarfile.is_tarfile('file') | Returns True if the file is a supported tar archive. |
| π Get a single member as a file object | tar.extractfile('member') | Returns an io.BufferedReader for regular files. |
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
CompressionErrorExtractErrorHeaderErrorReadErrorStreamErrorbuiltins.object
TarFileTarInfoTarError)All exception classes share the same method resolution order (TarError β builtins.Exception β builtins.BaseException β builtins.object) and inherit the following methods and data descriptors (listed once for TarError):
__init__(self, /, *args, **kwargs) β Initialize self.__new__(*args, **kwargs) from builtins.type β Create and return a new object.__delattr__(self, name, /) β Implement delattr(self, name).__getattribute__(self, name, /) β Return getattr(self, name).__reduce__(...) β Helper for pickle.__repr__(self, /) β Return repr(self).__setattr__(self, name, value, /) β Implement setattr(self, name, value).__setstate__(...)__str__(self, /) β Return str(self).with_traceback(...) β Set __traceback__ and return self.__weakref__, __cause__, __context__, __dict__, __suppress_context__, __traceback__, argsCompressionErrorException for unavailable compression methods.
ExtractErrorGeneral exception for extract errors.
HeaderErrorBase exception for header errors.
ReadErrorException for unreadable tar archives.
StreamErrorException for unsupported operations on stream-like TarFiles.
TarFile classTarFile(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) β Open an (uncompressed) tar archive name. mode is either 'r' to read, 'a' to append, or 'w' to create a new file. Defaults to 'r'.__iter__(self) β Provide an iterator object.add(self, name, arcname=None, recursive=True, *, filter=None) β Add the file name to the archive. arcname specifies an alternative name. Directories are added recursively by default. filter is a function that expects a TarInfo argument and returns the changed TarInfo (or None to exclude).addfile(self, tarinfo, fileobj=None) β Add the TarInfo object tarinfo to the archive. If fileobj is given, it should be a binary file, and tarinfo.size bytes are read from it.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.close(self) β Close the TarFile. In write-mode, two finishing zero blocks are appended.extract(self, member, path='', set_attrs=True, *, numeric_owner=False, filter=None) β Extract a member from the archive to the current working directory, using its full name. member may be a filename or TarInfo object. filter can be a function or string name of a common filter.extractall(self, path='.', members=None, *, numeric_owner=False, filter=None) β Extract all members from the archive to the current working directory. members is optional and must be a subset of getmembers().extractfile(self, member) β Extract a member as a file object. Returns an io.BufferedReader for regular files or links, None otherwise. Raises KeyError if not found.getmember(self, name) β Return a TarInfo object for member name. Raises KeyError if not found.getmembers(self) β Return the members of the archive as a list of TarInfo objects.getnames(self) β Return the members as a list of their names.gettarinfo(self, name=None, arcname=None, fileobj=None) β Create a TarInfo object from the result of os.stat on an existing file.list(self, verbose=True, *, members=None) β Print a table of contents to sys.stdout. If verbose is False, only names are printed.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.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, or None if no more.utime(self, tarinfo, targetpath) β Set modification time of targetpath according to tarinfo.bz2open(name, mode='r', fileobj=None, compresslevel=9, **kwargs) from builtins.type β Open bzip2 compressed tar archive for reading or writing. Appending is not allowed.gzopen(name, mode='r', fileobj=None, compresslevel=9, **kwargs) from builtins.type β Open gzip compressed tar archive for reading or writing. Appending is not allowed.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs) from builtins.type β Open a tar archive for reading, writing or appending. Returns an appropriate TarFile class. See mode descriptions below.taropen(name, mode='r', fileobj=None, **kwargs) from builtins.type β Open uncompressed tar archive for reading or writing.xzopen(name, mode='r', fileobj=None, preset=None, **kwargs) from builtins.type β Open lzma compressed tar archive for reading or writing. Appending is not allowed.__dict__ β dictionary for instance variables__weakref__ β list of weak referencesOPEN_METH = {'bz2': 'bz2open', 'gz': 'gzopen', 'tar': 'taropen', 'xz': 'xzopen'}debug = 0dereference = Falseencoding = 'utf-8'errorlevel = 1errors = Noneextraction_filter = Nonefileobject = <class 'tarfile.ExFileObject'>format = 2ignore_zeros = Falsetarinfo = <class 'tarfile.TarInfo'>TarInfo classTarInfo(name='')
Informational class which holds the details about an archive member given by a tar header block. Objects are returned by TarFile.getmember(), TarFile.getmembers() and TarFile.gettarinfo().
__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=..., mtime=..., mode=..., linkname=..., uid=..., gid=..., uname=..., gname=..., deep=True, _KEEP=...) β 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) from builtins.type β Return the object as a pax global header block sequence.frombuf(buf, encoding, errors) from builtins.type β Construct a TarInfo object from a 512 byte bytes object. Supports old v7 tar format headers.fromtarfile(tarfile) from builtins.type β 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 (only present for 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 of key-value pairs from an associated pax extended header.size β Size in bytes.sparse β Sparse member information.tarfiletype β File type (one of 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 descriptions:
'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 already exists'x:gz' β create a gzip compressed tarfile exclusively'x:bz2' β create a bzip2 compressed tarfile exclusively'x:xz' β create an lzma compressed tarfile exclusively'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 writingDEFAULT_FORMAT = 2ENCODING = 'utf-8'GNU_FORMAT = 1PAX_FORMAT = 2USTAR_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.10.0-7-g98e9fd5 · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-09-01 16:56 @216.73.216.239
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)