python-clinic / Doc / library / tarfile.rst

:mod:`tarfile` --- Read and write tar archive files

Source code: :source:`Lib/`

The :mod:`tarfile` module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the :mod:`zipfile` module to read or write :file:`.zip` files, or the higher-level functions in :ref:`shutil <archiving-operations>`.

Some facts and figures:

  • reads and writes :mod:`gzip`, :mod:`bz2` and :mod:`lzma` compressed archives.
  • read/write support for the POSIX.1-1988 (ustar) format.
  • read/write support for the GNU tar format including longname and longlink extensions, read-only support for all variants of the sparse extension including restoration of sparse files.
  • read/write support for the POSIX.1-2001 (pax) format.
  • handles directories, regular files, hardlinks, symbolic links, fifos, character devices and block devices and is able to acquire and restore file information like timestamp, access permissions and owner.

Class for reading and writing tar archives. Do not use this class directly, better use :func:`` instead. See :ref:`tarfile-objects`.

The :mod:`tarfile` module defines the following exceptions:

Each of the following constants defines a tar archive format that the :mod:`tarfile` module is able to create. See section :ref:`tar-formats` for details.

The following variables are available on module level:

TarFile Objects

The :class:`TarFile` object provides an interface to a tar archive. A tar archive is a sequence of blocks. An archive member (a stored file) is made up of a header block followed by data blocks. It is possible to store a file in a tar archive several times. Each archive member is represented by a :class:`TarInfo` object, see :ref:`tarinfo-objects` for details.

A :class:`TarFile` object can be used as a context manager in a :keyword:`with` statement. It will automatically be closed when the block is completed. Please note that in the event of an exception an archive opened for writing will not be finalized; only the internally used file object will be closed. See the :ref:`tar-examples` section for a use case.

All following arguments are optional and can be accessed as instance attributes as well.

name is the pathname of the archive. It can be omitted if fileobj is given. In this case, the file object's :attr:`name` attribute is used if it exists.

mode is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one.

If fileobj is given, it is used for reading or writing data. If it can be determined, mode is overridden by fileobj's mode. fileobj will be used from position 0.


fileobj is not closed, when :class:`TarFile` is closed.

format controls the archive format. It must be one of the constants :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are defined at module level.

The tarinfo argument can be used to replace the default :class:`TarInfo` class with a different one.

If dereference is :const:`False`, add symbolic and hard links to the archive. If it is :const:`True`, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links.

If ignore_zeros is :const:`False`, treat an empty block as the end of the archive. If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members as possible. This is only useful for reading concatenated or damaged archives.

debug can be set from 0 (no debug messages) up to 3 (all debug messages). The messages are written to sys.stderr.

If errorlevel is 0, all errors are ignored when using :meth:`TarFile.extract`. Nevertheless, they appear as error messages in the debug output, when debugging is enabled. If 1, all fatal errors are raised as :exc:`OSError` exceptions. If 2, all non-fatal errors are raised as :exc:`TarError` exceptions as well.

The encoding and errors arguments define the character encoding to be used for reading or writing the archive and how conversion errors are going to be handled. The default settings will work for most users. See section :ref:`tar-unicode` for in-depth information.

The pax_headers argument is an optional dictionary of strings which will be added as a pax global header if format is :const:`PAX_FORMAT`.

TarInfo Objects

A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside from storing all required attributes of a file (like file type, size, time, permissions, owner etc.), it provides some useful methods to determine its type. It does not contain the file's data itself.

:class:`TarInfo` objects are returned by :class:`TarFile`'s methods :meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.

Create a :class:`TarInfo` object.

A TarInfo object has the following public data attributes:

A :class:`TarInfo` object also provides some convenient query methods:


How to extract an entire tar archive to the current working directory:

import tarfile
tar ="sample.tar.gz")

How to extract a subset of a tar archive with :meth:`TarFile.extractall` using a generator function instead of a list:

import os
import tarfile

def py_files(members):
    for tarinfo in members:
        if os.path.splitext([1] == ".py":
            yield tarinfo

tar ="sample.tar.gz")

How to create an uncompressed tar archive from a list of filenames:

import tarfile
tar ="sample.tar", "w")
for name in ["foo", "bar", "quux"]:

The same example using the :keyword:`with` statement:

import tarfile
with"sample.tar", "w") as tar:
    for name in ["foo", "bar", "quux"]:

How to read a gzip compressed tar archive and display some member information:

import tarfile
tar ="sample.tar.gz", "r:gz")
for tarinfo in tar:
    print(, "is", tarinfo.size, "bytes in size and is", end="")
    if tarinfo.isreg():
        print("a regular file.")
    elif tarinfo.isdir():
        print("a directory.")
        print("something else.")

How to create an archive and reset the user information using the filter parameter in :meth:`TarFile.add`:

import tarfile
def reset(tarinfo):
    tarinfo.uid = tarinfo.gid = 0
    tarinfo.uname = tarinfo.gname = "root"
    return tarinfo
tar ="sample.tar.gz", "w:gz")
tar.add("foo", filter=reset)

Supported tar formats

There are three tar formats that can be created with the :mod:`tarfile` module:

  • The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames up to a length of at best 256 characters and linknames up to 100 characters. The maximum file size is 8 GiB. This is an old and limited but widely supported format.

  • The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and linknames, files bigger than 8 GiB and sparse files. It is the de facto standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar extensions for long names, sparse file support is read-only.

  • The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible format with virtually no limits. It supports long filenames and linknames, large files and stores pathnames in a portable way. However, not all tar implementations today are able to handle pax archives properly.

    The pax format is an extension to the existing ustar format. It uses extra headers for information that cannot be stored otherwise. There are two flavours of pax headers: Extended headers only affect the subsequent file header, global headers are valid for the complete archive and affect all following files. All the data in a pax header is encoded in UTF-8 for portability reasons.

There are some more variants of the tar format which can be read, but not created:

  • The ancient V7 format. This is the first tar format from Unix Seventh Edition, storing only regular files and directories. Names must not be longer than 100 characters, there is no user/group name information. Some archives have miscalculated header checksums in case of fields with non-ASCII characters.
  • The SunOS tar extended format. This format is a variant of the POSIX.1-2001 pax format, but is not compatible.

Unicode issues

The tar format was originally conceived to make backups on tape drives with the main focus on preserving file system information. Nowadays tar archives are commonly used for file distribution and exchanging archives over networks. One problem of the original format (which is the basis of all other formats) is that there is no concept of supporting different character encodings. For example, an ordinary tar archive created on a UTF-8 system cannot be read correctly on a Latin-1 system if it contains non-ASCII characters. Textual metadata (like filenames, linknames, user/group names) will appear damaged. Unfortunately, there is no way to autodetect the encoding of an archive. The pax format was designed to solve this problem. It stores non-ASCII metadata using the universal character encoding UTF-8.

The details of character conversion in :mod:`tarfile` are controlled by the encoding and errors keyword arguments of the :class:`TarFile` class.

encoding defines the character encoding to use for the metadata in the archive. The default value is :func:`sys.getfilesystemencoding` or 'ascii' as a fallback. Depending on whether the archive is read or written, the metadata must be either decoded or encoded. If encoding is not set appropriately, this conversion may fail.

The errors argument defines how characters are treated that cannot be converted. Possible values are listed in section :ref:`codec-base-classes`. The default scheme is 'surrogateescape' which Python also uses for its file system calls, see :ref:`os-filenames`.

In case of :const:`PAX_FORMAT` archives, encoding is generally not needed because all the metadata is stored using UTF-8. encoding is only used in the rare cases when binary pax headers are decoded or when strings with surrogate characters are stored.