diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Ftarfile.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Ftarfile.html')
| -rw-r--r-- | devdocs/python~3.12/library%2Ftarfile.html | 391 |
1 files changed, 391 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Ftarfile.html b/devdocs/python~3.12/library%2Ftarfile.html new file mode 100644 index 00000000..e5f2b0f6 --- /dev/null +++ b/devdocs/python~3.12/library%2Ftarfile.html @@ -0,0 +1,391 @@ + <span id="tarfile-read-and-write-tar-archive-files"></span><h1>tarfile — Read and write tar archive files</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/tarfile.py">Lib/tarfile.py</a></p> <p>The <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module makes it possible to read and write tar archives, including those using gzip, bz2 and lzma compression. Use the <a class="reference internal" href="zipfile#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code>zipfile</code></a> module to read or write <code>.zip</code> files, or the higher-level functions in <a class="reference internal" href="shutil#archiving-operations"><span class="std std-ref">shutil</span></a>.</p> <p>Some facts and figures:</p> <ul class="simple"> <li>reads and writes <a class="reference internal" href="gzip#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code>gzip</code></a>, <a class="reference internal" href="bz2#module-bz2" title="bz2: Interfaces for bzip2 compression and decompression."><code>bz2</code></a> and <a class="reference internal" href="lzma#module-lzma" title="lzma: A Python wrapper for the liblzma compression library."><code>lzma</code></a> compressed archives if the respective modules are available.</li> <li>read/write support for the POSIX.1-1988 (ustar) format.</li> <li>read/write support for the GNU tar format including <em>longname</em> and <em>longlink</em> extensions, read-only support for all variants of the <em>sparse</em> extension including restoration of sparse files.</li> <li>read/write support for the POSIX.1-2001 (pax) format.</li> <li>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.</li> </ul> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Added support for <a class="reference internal" href="lzma#module-lzma" title="lzma: A Python wrapper for the liblzma compression library."><code>lzma</code></a> compression.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Archives are extracted using a <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">filter</span></a>, which makes it possible to either limit surprising/dangerous features, or to acknowledge that they are expected and the archive is fully trusted. By default, archives are fully trusted, but this default is deprecated and slated to change in Python 3.14.</p> </div> <dl class="py function"> <dt class="sig sig-object py" id="tarfile.open"> +<code>tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)</code> </dt> <dd> +<p>Return a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> object for the pathname <em>name</em>. For detailed information on <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> objects and the keyword arguments that are allowed, see <a class="reference internal" href="#tarfile-objects"><span class="std std-ref">TarFile Objects</span></a>.</p> <p><em>mode</em> has to be a string of the form <code>'filemode[:compression]'</code>, it defaults to <code>'r'</code>. Here is a full list of mode combinations:</p> <table class="docutils align-default"> <thead> <tr> +<th class="head"><p>mode</p></th> <th class="head"><p>action</p></th> </tr> </thead> <tr> +<td><p><code>'r' or 'r:*'</code></p></td> <td><p>Open for reading with transparent compression (recommended).</p></td> </tr> <tr> +<td><p><code>'r:'</code></p></td> <td><p>Open for reading exclusively without compression.</p></td> </tr> <tr> +<td><p><code>'r:gz'</code></p></td> <td><p>Open for reading with gzip compression.</p></td> </tr> <tr> +<td><p><code>'r:bz2'</code></p></td> <td><p>Open for reading with bzip2 compression.</p></td> </tr> <tr> +<td><p><code>'r:xz'</code></p></td> <td><p>Open for reading with lzma compression.</p></td> </tr> <tr> +<td><p><code>'x'</code> or <code>'x:'</code></p></td> <td><p>Create a tarfile exclusively without compression. Raise a <a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> exception if it already exists.</p></td> </tr> <tr> +<td><p><code>'x:gz'</code></p></td> <td><p>Create a tarfile with gzip compression. Raise a <a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> exception if it already exists.</p></td> </tr> <tr> +<td><p><code>'x:bz2'</code></p></td> <td><p>Create a tarfile with bzip2 compression. Raise a <a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> exception if it already exists.</p></td> </tr> <tr> +<td><p><code>'x:xz'</code></p></td> <td><p>Create a tarfile with lzma compression. Raise a <a class="reference internal" href="exceptions#FileExistsError" title="FileExistsError"><code>FileExistsError</code></a> exception if it already exists.</p></td> </tr> <tr> +<td><p><code>'a' or 'a:'</code></p></td> <td><p>Open for appending with no compression. The file is created if it does not exist.</p></td> </tr> <tr> +<td><p><code>'w' or 'w:'</code></p></td> <td><p>Open for uncompressed writing.</p></td> </tr> <tr> +<td><p><code>'w:gz'</code></p></td> <td><p>Open for gzip compressed writing.</p></td> </tr> <tr> +<td><p><code>'w:bz2'</code></p></td> <td><p>Open for bzip2 compressed writing.</p></td> </tr> <tr> +<td><p><code>'w:xz'</code></p></td> <td><p>Open for lzma compressed writing.</p></td> </tr> </table> <p>Note that <code>'a:gz'</code>, <code>'a:bz2'</code> or <code>'a:xz'</code> is not possible. If <em>mode</em> is not suitable to open a certain (compressed) file for reading, <a class="reference internal" href="#tarfile.ReadError" title="tarfile.ReadError"><code>ReadError</code></a> is raised. Use <em>mode</em> <code>'r'</code> to avoid this. If a compression method is not supported, <a class="reference internal" href="#tarfile.CompressionError" title="tarfile.CompressionError"><code>CompressionError</code></a> is raised.</p> <p>If <em>fileobj</em> is specified, it is used as an alternative to a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> opened in binary mode for <em>name</em>. It is supposed to be at position 0.</p> <p>For modes <code>'w:gz'</code>, <code>'x:gz'</code>, <code>'w|gz'</code>, <code>'w:bz2'</code>, <code>'x:bz2'</code>, <code>'w|bz2'</code>, <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code>tarfile.open()</code></a> accepts the keyword argument <em>compresslevel</em> (default <code>9</code>) to specify the compression level of the file.</p> <p>For modes <code>'w:xz'</code> and <code>'x:xz'</code>, <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code>tarfile.open()</code></a> accepts the keyword argument <em>preset</em> to specify the compression level of the file.</p> <p>For special purposes, there is a second format for <em>mode</em>: <code>'filemode|[compression]'</code>. <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code>tarfile.open()</code></a> will return a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> object that processes its data as a stream of blocks. No random seeking will be done on the file. If given, <em>fileobj</em> may be any object that has a <a class="reference internal" href="io#io.RawIOBase.read" title="io.RawIOBase.read"><code>read()</code></a> or <a class="reference internal" href="io#io.RawIOBase.write" title="io.RawIOBase.write"><code>write()</code></a> method (depending on the <em>mode</em>) that works with bytes. <em>bufsize</em> specifies the blocksize and defaults to <code>20 * 512</code> bytes. Use this variant in combination with e.g. <code>sys.stdin.buffer</code>, a socket <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> or a tape device. However, such a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> object is limited in that it does not allow random access, see <a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a>. The currently possible modes:</p> <table class="docutils align-default"> <thead> <tr> +<th class="head"><p>Mode</p></th> <th class="head"><p>Action</p></th> </tr> </thead> <tr> +<td><p><code>'r|*'</code></p></td> <td><p>Open a <em>stream</em> of tar blocks for reading with transparent compression.</p></td> </tr> <tr> +<td><p><code>'r|'</code></p></td> <td><p>Open a <em>stream</em> of uncompressed tar blocks for reading.</p></td> </tr> <tr> +<td><p><code>'r|gz'</code></p></td> <td><p>Open a gzip compressed <em>stream</em> for reading.</p></td> </tr> <tr> +<td><p><code>'r|bz2'</code></p></td> <td><p>Open a bzip2 compressed <em>stream</em> for reading.</p></td> </tr> <tr> +<td><p><code>'r|xz'</code></p></td> <td><p>Open an lzma compressed <em>stream</em> for reading.</p></td> </tr> <tr> +<td><p><code>'w|'</code></p></td> <td><p>Open an uncompressed <em>stream</em> for writing.</p></td> </tr> <tr> +<td><p><code>'w|gz'</code></p></td> <td><p>Open a gzip compressed <em>stream</em> for writing.</p></td> </tr> <tr> +<td><p><code>'w|bz2'</code></p></td> <td><p>Open a bzip2 compressed <em>stream</em> for writing.</p></td> </tr> <tr> +<td><p><code>'w|xz'</code></p></td> <td><p>Open an lzma compressed <em>stream</em> for writing.</p></td> </tr> </table> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <code>'x'</code> (exclusive creation) mode was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>name</em> parameter accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The <em>compresslevel</em> keyword argument also works for streams.</p> </div> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py"> <em class="property">class<span class="w"> </span></em><span class="sig-prename descclassname">tarfile.</span><span class="sig-name descname">TarFile</span> +</dt> <dd> +<p>Class for reading and writing tar archives. Do not use this class directly: use <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code>tarfile.open()</code></a> instead. See <a class="reference internal" href="#tarfile-objects"><span class="std std-ref">TarFile Objects</span></a>.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="tarfile.is_tarfile"> +<code>tarfile.is_tarfile(name)</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if <em>name</em> is a tar archive file, that the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module can read. <em>name</em> may be a <a class="reference internal" href="stdtypes#str" title="str"><code>str</code></a>, file, or file-like object.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Support for file and file-like objects.</p> </div> </dd> +</dl> <p>The <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module defines the following exceptions:</p> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.TarError"> +<code>exception tarfile.TarError</code> </dt> <dd> +<p>Base class for all <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> exceptions.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.ReadError"> +<code>exception tarfile.ReadError</code> </dt> <dd> +<p>Is raised when a tar archive is opened, that either cannot be handled by the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module or is somehow invalid.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.CompressionError"> +<code>exception tarfile.CompressionError</code> </dt> <dd> +<p>Is raised when a compression method is not supported or when the data cannot be decoded properly.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.StreamError"> +<code>exception tarfile.StreamError</code> </dt> <dd> +<p>Is raised for the limitations that are typical for stream-like <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> objects.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.ExtractError"> +<code>exception tarfile.ExtractError</code> </dt> <dd> +<p>Is raised for <em>non-fatal</em> errors when using <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>TarFile.extract()</code></a>, but only if <a class="reference internal" href="#tarfile.TarFile.errorlevel" title="tarfile.TarFile.errorlevel"><code>TarFile.errorlevel</code></a><code>== 2</code>.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.HeaderError"> +<code>exception tarfile.HeaderError</code> </dt> <dd> +<p>Is raised by <a class="reference internal" href="#tarfile.TarInfo.frombuf" title="tarfile.TarInfo.frombuf"><code>TarInfo.frombuf()</code></a> if the buffer it gets is invalid.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.FilterError"> +<code>exception tarfile.FilterError</code> </dt> <dd> +<p>Base class for members <a class="reference internal" href="#tarfile-extraction-refuse"><span class="std std-ref">refused</span></a> by filters.</p> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.FilterError.tarinfo"> +<code>tarinfo</code> </dt> <dd> +<p>Information about the member that the filter refused to extract, as <a class="reference internal" href="#tarinfo-objects"><span class="std std-ref">TarInfo</span></a>.</p> </dd> +</dl> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.AbsolutePathError"> +<code>exception tarfile.AbsolutePathError</code> </dt> <dd> +<p>Raised to refuse extracting a member with an absolute path.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.OutsideDestinationError"> +<code>exception tarfile.OutsideDestinationError</code> </dt> <dd> +<p>Raised to refuse extracting a member outside the destination directory.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.SpecialFileError"> +<code>exception tarfile.SpecialFileError</code> </dt> <dd> +<p>Raised to refuse extracting a special file (e.g. a device or pipe).</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.AbsoluteLinkError"> +<code>exception tarfile.AbsoluteLinkError</code> </dt> <dd> +<p>Raised to refuse extracting a symbolic link with an absolute path.</p> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="tarfile.LinkOutsideDestinationError"> +<code>exception tarfile.LinkOutsideDestinationError</code> </dt> <dd> +<p>Raised to refuse extracting a symbolic link pointing outside the destination directory.</p> </dd> +</dl> <p>The following constants are available at the module level:</p> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.ENCODING"> +<code>tarfile.ENCODING</code> </dt> <dd> +<p>The default character encoding: <code>'utf-8'</code> on Windows, the value returned by <a class="reference internal" href="sys#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code>sys.getfilesystemencoding()</code></a> otherwise.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.REGTYPE"> +<code>tarfile.REGTYPE</code> </dt> <dt class="sig sig-object py" id="tarfile.AREGTYPE"> +<code>tarfile.AREGTYPE</code> </dt> <dd> +<p>A regular file <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.LNKTYPE"> +<code>tarfile.LNKTYPE</code> </dt> <dd> +<p>A link (inside tarfile) <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.SYMTYPE"> +<code>tarfile.SYMTYPE</code> </dt> <dd> +<p>A symbolic link <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.CHRTYPE"> +<code>tarfile.CHRTYPE</code> </dt> <dd> +<p>A character special device <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.BLKTYPE"> +<code>tarfile.BLKTYPE</code> </dt> <dd> +<p>A block special device <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.DIRTYPE"> +<code>tarfile.DIRTYPE</code> </dt> <dd> +<p>A directory <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.FIFOTYPE"> +<code>tarfile.FIFOTYPE</code> </dt> <dd> +<p>A FIFO special device <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.CONTTYPE"> +<code>tarfile.CONTTYPE</code> </dt> <dd> +<p>A contiguous file <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.GNUTYPE_LONGNAME"> +<code>tarfile.GNUTYPE_LONGNAME</code> </dt> <dd> +<p>A GNU tar longname <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.GNUTYPE_LONGLINK"> +<code>tarfile.GNUTYPE_LONGLINK</code> </dt> <dd> +<p>A GNU tar longlink <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.GNUTYPE_SPARSE"> +<code>tarfile.GNUTYPE_SPARSE</code> </dt> <dd> +<p>A GNU tar sparse file <a class="reference internal" href="#tarfile.TarInfo.type" title="tarfile.TarInfo.type"><code>type</code></a>.</p> </dd> +</dl> <p>Each of the following constants defines a tar archive format that the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module is able to create. See section <a class="reference internal" href="#tar-formats"><span class="std std-ref">Supported tar formats</span></a> for details.</p> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.USTAR_FORMAT"> +<code>tarfile.USTAR_FORMAT</code> </dt> <dd> +<p>POSIX.1-1988 (ustar) format.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.GNU_FORMAT"> +<code>tarfile.GNU_FORMAT</code> </dt> <dd> +<p>GNU tar format.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.PAX_FORMAT"> +<code>tarfile.PAX_FORMAT</code> </dt> <dd> +<p>POSIX.1-2001 (pax) format.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="tarfile.DEFAULT_FORMAT"> +<code>tarfile.DEFAULT_FORMAT</code> </dt> <dd> +<p>The default format for creating archives. This is currently <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>The default format for new archives was changed to <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a> from <a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code>GNU_FORMAT</code></a>.</p> </div> </dd> +</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt> +<code>Module</code> <a class="reference internal" href="zipfile#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code>zipfile</code></a> +</dt> +<dd> +<p>Documentation of the <a class="reference internal" href="zipfile#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code>zipfile</code></a> standard module.</p> </dd> <dt><a class="reference internal" href="shutil#archiving-operations"><span class="std std-ref">Archiving operations</span></a></dt> +<dd> +<p>Documentation of the higher-level archiving facilities provided by the standard <a class="reference internal" href="shutil#module-shutil" title="shutil: High-level file operations, including copying."><code>shutil</code></a> module.</p> </dd> <dt><a class="reference external" href="https://www.gnu.org/software/tar/manual/html_node/Standard.html">GNU tar manual, Basic Tar Format</a></dt> +<dd> +<p>Documentation for tar archive files, including GNU tar extensions.</p> </dd> </dl> </div> <section id="tarfile-objects"> <span id="id1"></span><h2>TarFile Objects</h2> <p>The <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> 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 <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object, see <a class="reference internal" href="#tarinfo-objects"><span class="std std-ref">TarInfo Objects</span></a> for details.</p> <p>A <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> object can be used as a context manager in a <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a> 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 <a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a> section for a use case.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.2: </span>Added support for the context management protocol.</p> </div> <dl class="py class"> <dt class="sig sig-object py" id="tarfile.TarFile"> +<code>class tarfile.TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors='surrogateescape', pax_headers=None, debug=0, errorlevel=1)</code> </dt> <dd> +<p>All following arguments are optional and can be accessed as instance attributes as well.</p> <p><em>name</em> is the pathname of the archive. <em>name</em> may be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>. It can be omitted if <em>fileobj</em> is given. In this case, the file object’s <code>name</code> attribute is used if it exists.</p> <p><em>mode</em> is either <code>'r'</code> to read from an existing archive, <code>'a'</code> to append data to an existing file, <code>'w'</code> to create a new file overwriting an existing one, or <code>'x'</code> to create a new file only if it does not already exist.</p> <p>If <em>fileobj</em> is given, it is used for reading or writing data. If it can be determined, <em>mode</em> is overridden by <em>fileobj</em>’s mode. <em>fileobj</em> will be used from position 0.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><em>fileobj</em> is not closed, when <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> is closed.</p> </div> <p><em>format</em> controls the archive format for writing. It must be one of the constants <a class="reference internal" href="#tarfile.USTAR_FORMAT" title="tarfile.USTAR_FORMAT"><code>USTAR_FORMAT</code></a>, <a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code>GNU_FORMAT</code></a> or <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a> that are defined at module level. When reading, format will be automatically detected, even if different formats are present in a single archive.</p> <p>The <em>tarinfo</em> argument can be used to replace the default <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> class with a different one.</p> <p>If <em>dereference</em> is <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, add symbolic and hard links to the archive. If it is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, add the content of the target files to the archive. This has no effect on systems that do not support symbolic links.</p> <p>If <em>ignore_zeros</em> is <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, treat an empty block as the end of the archive. If it is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, skip empty (and invalid) blocks and try to get as many members as possible. This is only useful for reading concatenated or damaged archives.</p> <p><em>debug</em> can be set from <code>0</code> (no debug messages) up to <code>3</code> (all debug messages). The messages are written to <code>sys.stderr</code>.</p> <p><em>errorlevel</em> controls how extraction errors are handled, see <a class="reference internal" href="#tarfile.TarFile.errorlevel" title="tarfile.TarFile.errorlevel"><code>the corresponding attribute</code></a>.</p> <p>The <em>encoding</em> and <em>errors</em> 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 <a class="reference internal" href="#tar-unicode"><span class="std std-ref">Unicode issues</span></a> for in-depth information.</p> <p>The <em>pax_headers</em> argument is an optional dictionary of strings which will be added as a pax global header if <em>format</em> is <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Use <code>'surrogateescape'</code> as the default for the <em>errors</em> argument.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>The <code>'x'</code> (exclusive creation) mode was added.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>name</em> parameter accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.open"> +<code>classmethod TarFile.open(...)</code> </dt> <dd> +<p>Alternative constructor. The <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code>tarfile.open()</code></a> function is actually a shortcut to this classmethod.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.getmember"> +<code>TarFile.getmember(name)</code> </dt> <dd> +<p>Return a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object for member <em>name</em>. If <em>name</em> can not be found in the archive, <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a> is raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If a member occurs more than once in the archive, its last occurrence is assumed to be the most up-to-date version.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.getmembers"> +<code>TarFile.getmembers()</code> </dt> <dd> +<p>Return the members of the archive as a list of <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> objects. The list has the same order as the members in the archive.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.getnames"> +<code>TarFile.getnames()</code> </dt> <dd> +<p>Return the members as a list of their names. It has the same order as the list returned by <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code>getmembers()</code></a>.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.list"> +<code>TarFile.list(verbose=True, *, members=None)</code> </dt> <dd> +<p>Print a table of contents to <code>sys.stdout</code>. If <em>verbose</em> is <a class="reference internal" href="constants#False" title="False"><code>False</code></a>, only the names of the members are printed. If it is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, output similar to that of <strong class="program">ls -l</strong> is produced. If optional <em>members</em> is given, it must be a subset of the list returned by <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code>getmembers()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added the <em>members</em> parameter.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.next"> +<code>TarFile.next()</code> </dt> <dd> +<p>Return the next member of the archive as a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object, when <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> is opened for reading. Return <a class="reference internal" href="constants#None" title="None"><code>None</code></a> if there is no more available.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.extractall"> +<code>TarFile.extractall(path='.', members=None, *, numeric_owner=False, filter=None)</code> </dt> <dd> +<p>Extract all members from the archive to the current working directory or directory <em>path</em>. If optional <em>members</em> is given, it must be a subset of the list returned by <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code>getmembers()</code></a>. Directory information like owner, modification time and permissions are set after all members have been extracted. This is done to work around two problems: A directory’s modification time is reset each time a file is created in it. And, if a directory’s permissions do not allow writing, extracting files to it will fail.</p> <p>If <em>numeric_owner</em> is <a class="reference internal" href="constants#True" title="True"><code>True</code></a>, the uid and gid numbers from the tarfile are used to set the owner/group for the extracted files. Otherwise, the named values from the tarfile are used.</p> <p>The <em>filter</em> argument specifies how <code>members</code> are modified or rejected before extraction. See <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">Extraction filters</span></a> for details. It is recommended to set this explicitly depending on which <em>tar</em> features you need to support.</p> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of <em>path</em>, e.g. members that have absolute filenames starting with <code>"/"</code> or filenames with two dots <code>".."</code>.</p> <p>Set <code>filter='data'</code> to prevent the most dangerous security issues, and read the <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">Extraction filters</span></a> section for details.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added the <em>numeric_owner</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>path</em> parameter accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>filter</em> parameter.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.extract"> +<code>TarFile.extract(member, path='', set_attrs=True, *, numeric_owner=False, filter=None)</code> </dt> <dd> +<p>Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. <em>member</em> may be a filename or a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object. You can specify a different directory using <em>path</em>. <em>path</em> may be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>. File attributes (owner, mtime, mode) are set unless <em>set_attrs</em> is false.</p> <p>The <em>numeric_owner</em> and <em>filter</em> arguments are the same as for <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> method does not take care of several extraction issues. In most cases you should consider using the <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a> method.</p> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>See the warning for <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>.</p> <p>Set <code>filter='data'</code> to prevent the most dangerous security issues, and read the <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">Extraction filters</span></a> section for details.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added the <em>set_attrs</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>Added the <em>numeric_owner</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>path</em> parameter accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>filter</em> parameter.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.extractfile"> +<code>TarFile.extractfile(member)</code> </dt> <dd> +<p>Extract a member from the archive as a file object. <em>member</em> may be a filename or a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object. If <em>member</em> is a regular file or a link, an <a class="reference internal" href="io#io.BufferedReader" title="io.BufferedReader"><code>io.BufferedReader</code></a> object is returned. For all other existing members, <a class="reference internal" href="constants#None" title="None"><code>None</code></a> is returned. If <em>member</em> does not appear in the archive, <a class="reference internal" href="exceptions#KeyError" title="KeyError"><code>KeyError</code></a> is raised.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Return an <a class="reference internal" href="io#io.BufferedReader" title="io.BufferedReader"><code>io.BufferedReader</code></a> object.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarFile.errorlevel"> +<code>TarFile.errorlevel: int</code> </dt> <dd> +<p>If <em>errorlevel</em> is <code>0</code>, errors are ignored when using <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>TarFile.extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>TarFile.extractall()</code></a>. Nevertheless, they appear as error messages in the debug output when <em>debug</em> is greater than 0. If <code>1</code> (the default), all <em>fatal</em> errors are raised as <a class="reference internal" href="exceptions#OSError" title="OSError"><code>OSError</code></a> or <a class="reference internal" href="#tarfile.FilterError" title="tarfile.FilterError"><code>FilterError</code></a> exceptions. If <code>2</code>, all <em>non-fatal</em> errors are raised as <a class="reference internal" href="#tarfile.TarError" title="tarfile.TarError"><code>TarError</code></a> exceptions as well.</p> <p>Some exceptions, e.g. ones caused by wrong argument types or data corruption, are always raised.</p> <p>Custom <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">extraction filters</span></a> should raise <a class="reference internal" href="#tarfile.FilterError" title="tarfile.FilterError"><code>FilterError</code></a> for <em>fatal</em> errors and <a class="reference internal" href="#tarfile.ExtractError" title="tarfile.ExtractError"><code>ExtractError</code></a> for <em>non-fatal</em> ones.</p> <p>Note that when an exception is raised, the archive may be partially extracted. It is the user’s responsibility to clean up.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarFile.extraction_filter"> +<code>TarFile.extraction_filter</code> </dt> <dd> +<div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <p>The <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">extraction filter</span></a> used as a default for the <em>filter</em> argument of <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>.</p> <p>The attribute may be <code>None</code> or a callable. String names are not allowed for this attribute, unlike the <em>filter</em> argument to <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a>.</p> <p>If <code>extraction_filter</code> is <code>None</code> (the default), calling an extraction method without a <em>filter</em> argument will raise a <code>DeprecationWarning</code>, and fall back to the <a class="reference internal" href="#tarfile.fully_trusted_filter" title="tarfile.fully_trusted_filter"><code>fully_trusted</code></a> filter, whose dangerous behavior matches previous versions of Python.</p> <p>In Python 3.14+, leaving <code>extraction_filter=None</code> will cause extraction methods to use the <a class="reference internal" href="#tarfile.data_filter" title="tarfile.data_filter"><code>data</code></a> filter by default.</p> <p>The attribute may be set on instances or overridden in subclasses. It also is possible to set it on the <code>TarFile</code> class itself to set a global default, although, since it affects all uses of <em>tarfile</em>, it is best practice to only do so in top-level applications or <a class="reference internal" href="site#module-site" title="site: Module responsible for site-specific configuration."><code>site configuration</code></a>. To set a global default this way, a filter function needs to be wrapped in <a class="reference internal" href="functions#staticmethod" title="staticmethod"><code>staticmethod()</code></a> to prevent injection of a <code>self</code> argument.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.add"> +<code>TarFile.add(name, arcname=None, recursive=True, *, filter=None)</code> </dt> <dd> +<p>Add the file <em>name</em> to the archive. <em>name</em> may be any type of file (directory, fifo, symbolic link, etc.). If given, <em>arcname</em> specifies an alternative name for the file in the archive. Directories are added recursively by default. This can be avoided by setting <em>recursive</em> to <a class="reference internal" href="constants#False" title="False"><code>False</code></a>. Recursion adds entries in sorted order. If <em>filter</em> is given, it should be a function that takes a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object argument and returns the changed <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object. If it instead returns <a class="reference internal" href="constants#None" title="None"><code>None</code></a> the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object will be excluded from the archive. See <a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a> for an example.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Added the <em>filter</em> parameter.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Recursion adds entries in sorted order.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.addfile"> +<code>TarFile.addfile(tarinfo, fileobj=None)</code> </dt> <dd> +<p>Add the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object <em>tarinfo</em> to the archive. If <em>fileobj</em> is given, it should be a <a class="reference internal" href="../glossary#term-binary-file"><span class="xref std std-term">binary file</span></a>, and <code>tarinfo.size</code> bytes are read from it and added to the archive. You can create <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> objects directly, or by using <a class="reference internal" href="#tarfile.TarFile.gettarinfo" title="tarfile.TarFile.gettarinfo"><code>gettarinfo()</code></a>.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.gettarinfo"> +<code>TarFile.gettarinfo(name=None, arcname=None, fileobj=None)</code> </dt> <dd> +<p>Create a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object from the result of <a class="reference internal" href="os#os.stat" title="os.stat"><code>os.stat()</code></a> or equivalent on an existing file. The file is either named by <em>name</em>, or specified as a <a class="reference internal" href="../glossary#term-file-object"><span class="xref std std-term">file object</span></a> <em>fileobj</em> with a file descriptor. <em>name</em> may be a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>. If given, <em>arcname</em> specifies an alternative name for the file in the archive, otherwise, the name is taken from <em>fileobj</em>’s <a class="reference internal" href="io#io.FileIO.name" title="io.FileIO.name"><code>name</code></a> attribute, or the <em>name</em> argument. The name should be a text string.</p> <p>You can modify some of the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a>’s attributes before you add it using <a class="reference internal" href="#tarfile.TarFile.addfile" title="tarfile.TarFile.addfile"><code>addfile()</code></a>. If the file object is not an ordinary file object positioned at the beginning of the file, attributes such as <a class="reference internal" href="#tarfile.TarInfo.size" title="tarfile.TarInfo.size"><code>size</code></a> may need modifying. This is the case for objects such as <a class="reference internal" href="gzip#gzip.GzipFile" title="gzip.GzipFile"><code>GzipFile</code></a>. The <a class="reference internal" href="#tarfile.TarInfo.name" title="tarfile.TarInfo.name"><code>name</code></a> may also be modified, in which case <em>arcname</em> could be a dummy string.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>name</em> parameter accepts a <a class="reference internal" href="../glossary#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p> </div> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarFile.close"> +<code>TarFile.close()</code> </dt> <dd> +<p>Close the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a>. In write mode, two finishing zero blocks are appended to the archive.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarFile.pax_headers"> +<code>TarFile.pax_headers</code> </dt> <dd> +<p>A dictionary containing key-value pairs of pax global headers.</p> </dd> +</dl> </section> <section id="tarinfo-objects"> <span id="id2"></span><h2>TarInfo Objects</h2> <p>A <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object represents one member in a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a>. 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 <em>not</em> contain the file’s data itself.</p> <p><a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> objects are returned by <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a>’s methods <a class="reference internal" href="#tarfile.TarFile.getmember" title="tarfile.TarFile.getmember"><code>getmember()</code></a>, <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code>getmembers()</code></a> and <a class="reference internal" href="#tarfile.TarFile.gettarinfo" title="tarfile.TarFile.gettarinfo"><code>gettarinfo()</code></a>.</p> <p>Modifying the objects returned by <a class="reference internal" href="#tarfile.TarFile.getmember" title="tarfile.TarFile.getmember"><code>getmember()</code></a> or <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code>getmembers()</code></a> will affect all subsequent operations on the archive. For cases where this is unwanted, you can use <a class="reference internal" href="copy#module-copy" title="copy: Shallow and deep copy operations."><code>copy.copy()</code></a> or call the <a class="reference internal" href="#tarfile.TarInfo.replace" title="tarfile.TarInfo.replace"><code>replace()</code></a> method to create a modified copy in one step.</p> <p>Several attributes can be set to <code>None</code> to indicate that a piece of metadata is unused or unknown. Different <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> methods handle <code>None</code> differently:</p> <ul class="simple"> <li>The <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> or <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a> methods will ignore the corresponding metadata, leaving it set to a default.</li> <li> +<a class="reference internal" href="#tarfile.TarFile.addfile" title="tarfile.TarFile.addfile"><code>addfile()</code></a> will fail.</li> <li> +<a class="reference internal" href="#tarfile.TarFile.list" title="tarfile.TarFile.list"><code>list()</code></a> will print a placeholder string.</li> </ul> <dl class="py class"> <dt class="sig sig-object py" id="tarfile.TarInfo"> +<code>class tarfile.TarInfo(name='')</code> </dt> <dd> +<p>Create a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.frombuf"> +<code>classmethod TarInfo.frombuf(buf, encoding, errors)</code> </dt> <dd> +<p>Create and return a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object from string buffer <em>buf</em>.</p> <p>Raises <a class="reference internal" href="#tarfile.HeaderError" title="tarfile.HeaderError"><code>HeaderError</code></a> if the buffer is invalid.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.fromtarfile"> +<code>classmethod TarInfo.fromtarfile(tarfile)</code> </dt> <dd> +<p>Read the next member from the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> object <em>tarfile</em> and return it as a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.tobuf"> +<code>TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')</code> </dt> <dd> +<p>Create a string buffer from a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object. For information on the arguments see the constructor of the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> class.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.2: </span>Use <code>'surrogateescape'</code> as the default for the <em>errors</em> argument.</p> </div> </dd> +</dl> <p>A <code>TarInfo</code> object has the following public data attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.name"> +<code>TarInfo.name: str</code> </dt> <dd> +<p>Name of the archive member.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.size"> +<code>TarInfo.size: int</code> </dt> <dd> +<p>Size in bytes.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.mtime"> +<code>TarInfo.mtime: int | float</code> </dt> <dd> +<p>Time of last modification in seconds since the <a class="reference internal" href="time#epoch"><span class="std std-ref">epoch</span></a>, as in <a class="reference internal" href="os#os.stat_result.st_mtime" title="os.stat_result.st_mtime"><code>os.stat_result.st_mtime</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.mode"> +<code>TarInfo.mode: int</code> </dt> <dd> +<p>Permission bits, as for <a class="reference internal" href="os#os.chmod" title="os.chmod"><code>os.chmod()</code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.type"> +<code>TarInfo.type</code> </dt> <dd> +<p>File type. <em>type</em> is usually one of these constants: <a class="reference internal" href="#tarfile.REGTYPE" title="tarfile.REGTYPE"><code>REGTYPE</code></a>, <a class="reference internal" href="#tarfile.AREGTYPE" title="tarfile.AREGTYPE"><code>AREGTYPE</code></a>, <a class="reference internal" href="#tarfile.LNKTYPE" title="tarfile.LNKTYPE"><code>LNKTYPE</code></a>, <a class="reference internal" href="#tarfile.SYMTYPE" title="tarfile.SYMTYPE"><code>SYMTYPE</code></a>, <a class="reference internal" href="#tarfile.DIRTYPE" title="tarfile.DIRTYPE"><code>DIRTYPE</code></a>, <a class="reference internal" href="#tarfile.FIFOTYPE" title="tarfile.FIFOTYPE"><code>FIFOTYPE</code></a>, <a class="reference internal" href="#tarfile.CONTTYPE" title="tarfile.CONTTYPE"><code>CONTTYPE</code></a>, <a class="reference internal" href="#tarfile.CHRTYPE" title="tarfile.CHRTYPE"><code>CHRTYPE</code></a>, <a class="reference internal" href="#tarfile.BLKTYPE" title="tarfile.BLKTYPE"><code>BLKTYPE</code></a>, <a class="reference internal" href="#tarfile.GNUTYPE_SPARSE" title="tarfile.GNUTYPE_SPARSE"><code>GNUTYPE_SPARSE</code></a>. To determine the type of a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object more conveniently, use the <code>is*()</code> methods below.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.linkname"> +<code>TarInfo.linkname: str</code> </dt> <dd> +<p>Name of the target file name, which is only present in <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> objects of type <a class="reference internal" href="#tarfile.LNKTYPE" title="tarfile.LNKTYPE"><code>LNKTYPE</code></a> and <a class="reference internal" href="#tarfile.SYMTYPE" title="tarfile.SYMTYPE"><code>SYMTYPE</code></a>.</p> <p>For symbolic links (<code>SYMTYPE</code>), the <em>linkname</em> is relative to the directory that contains the link. For hard links (<code>LNKTYPE</code>), the <em>linkname</em> is relative to the root of the archive.</p> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.uid"> +<code>TarInfo.uid: int</code> </dt> <dd> +<p>User ID of the user who originally stored this member.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.gid"> +<code>TarInfo.gid: int</code> </dt> <dd> +<p>Group ID of the user who originally stored this member.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.uname"> +<code>TarInfo.uname: str</code> </dt> <dd> +<p>User name.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.gname"> +<code>TarInfo.gname: str</code> </dt> <dd> +<p>Group name.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Can be set to <code>None</code> for <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>extract()</code></a> and <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a>, causing extraction to skip applying this attribute.</p> </div> </dd> +</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="tarfile.TarInfo.pax_headers"> +<code>TarInfo.pax_headers: dict</code> </dt> <dd> +<p>A dictionary containing key-value pairs of an associated pax extended header.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.replace"> +<code>TarInfo.replace(name=..., mtime=..., mode=..., linkname=..., uid=..., gid=..., uname=..., gname=..., deep=True)</code> </dt> <dd> +<div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <p>Return a <em>new</em> copy of the <code>TarInfo</code> object with the given attributes changed. For example, to return a <code>TarInfo</code> with the group name set to <code>'staff'</code>, use:</p> <pre data-language="python">new_tarinfo = old_tarinfo.replace(gname='staff') +</pre> <p>By default, a deep copy is made. If <em>deep</em> is false, the copy is shallow, i.e. <code>pax_headers</code> and any custom attributes are shared with the original <code>TarInfo</code> object.</p> </dd> +</dl> <p>A <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object also provides some convenient query methods:</p> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isfile"> +<code>TarInfo.isfile()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object is a regular file.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isreg"> +<code>TarInfo.isreg()</code> </dt> <dd> +<p>Same as <a class="reference internal" href="#tarfile.TarInfo.isfile" title="tarfile.TarInfo.isfile"><code>isfile()</code></a>.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isdir"> +<code>TarInfo.isdir()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a directory.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.issym"> +<code>TarInfo.issym()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a symbolic link.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.islnk"> +<code>TarInfo.islnk()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a hard link.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.ischr"> +<code>TarInfo.ischr()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a character device.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isblk"> +<code>TarInfo.isblk()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a block device.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isfifo"> +<code>TarInfo.isfifo()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is a FIFO.</p> </dd> +</dl> <dl class="py method"> <dt class="sig sig-object py" id="tarfile.TarInfo.isdev"> +<code>TarInfo.isdev()</code> </dt> <dd> +<p>Return <a class="reference internal" href="constants#True" title="True"><code>True</code></a> if it is one of character device, block device or FIFO.</p> </dd> +</dl> </section> <section id="extraction-filters"> <span id="tarfile-extraction-filter"></span><h2>Extraction filters</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.12.</span></p> </div> <p>The <em>tar</em> format is designed to capture all details of a UNIX-like filesystem, which makes it very powerful. Unfortunately, the features make it easy to create tar files that have unintended – and possibly malicious – effects when extracted. For example, extracting a tar file can overwrite arbitrary files in various ways (e.g. by using absolute paths, <code>..</code> path components, or symlinks that affect later members).</p> <p>In most cases, the full functionality is not needed. Therefore, <em>tarfile</em> supports extraction filters: a mechanism to limit functionality, and thus mitigate some of the security issues.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt> +<span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0706/"><strong>PEP 706</strong></a> +</dt> +<dd> +<p>Contains further motivation and rationale behind the design.</p> </dd> </dl> </div> <p>The <em>filter</em> argument to <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code>TarFile.extract()</code></a> or <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a> can be:</p> <ul> <li>the string <code>'fully_trusted'</code>: Honor all metadata as specified in the archive. Should be used if the user trusts the archive completely, or implements their own complex verification.</li> <li>the string <code>'tar'</code>: Honor most <em>tar</em>-specific features (i.e. features of UNIX-like filesystems), but block features that are very likely to be surprising or malicious. See <a class="reference internal" href="#tarfile.tar_filter" title="tarfile.tar_filter"><code>tar_filter()</code></a> for details.</li> <li>the string <code>'data'</code>: Ignore or block most features specific to UNIX-like filesystems. Intended for extracting cross-platform data archives. See <a class="reference internal" href="#tarfile.data_filter" title="tarfile.data_filter"><code>data_filter()</code></a> for details.</li> <li> +<p><code>None</code> (default): Use <a class="reference internal" href="#tarfile.TarFile.extraction_filter" title="tarfile.TarFile.extraction_filter"><code>TarFile.extraction_filter</code></a>.</p> <p>If that is also <code>None</code> (the default), raise a <code>DeprecationWarning</code>, and fall back to the <code>'fully_trusted'</code> filter, whose dangerous behavior matches previous versions of Python.</p> <p>In Python 3.14, the <code>'data'</code> filter will become the default instead. It’s possible to switch earlier; see <a class="reference internal" href="#tarfile.TarFile.extraction_filter" title="tarfile.TarFile.extraction_filter"><code>TarFile.extraction_filter</code></a>.</p> </li> <li> +<p>A callable which will be called for each extracted member with a <a class="reference internal" href="#tarinfo-objects"><span class="std std-ref">TarInfo</span></a> describing the member and the destination path to where the archive is extracted (i.e. the same path is used for all members):</p> <pre data-language="python">filter(member: TarInfo, path: str, /) -> TarInfo | None +</pre> <p>The callable is called just before each member is extracted, so it can take the current state of the disk into account. It can:</p> <ul class="simple"> <li>return a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code>TarInfo</code></a> object which will be used instead of the metadata in the archive, or</li> <li>return <code>None</code>, in which case the member will be skipped, or</li> <li>raise an exception to abort the operation or skip the member, depending on <a class="reference internal" href="#tarfile.TarFile.errorlevel" title="tarfile.TarFile.errorlevel"><code>errorlevel</code></a>. Note that when extraction is aborted, <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>extractall()</code></a> may leave the archive partially extracted. It does not attempt to clean up.</li> </ul> </li> </ul> <section id="default-named-filters"> <h3>Default named filters</h3> <p>The pre-defined, named filters are available as functions, so they can be reused in custom filters:</p> <dl class="py function"> <dt class="sig sig-object py" id="tarfile.fully_trusted_filter"> +<code>tarfile.fully_trusted_filter(member, path)</code> </dt> <dd> +<p>Return <em>member</em> unchanged.</p> <p>This implements the <code>'fully_trusted'</code> filter.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="tarfile.tar_filter"> +<code>tarfile.tar_filter(member, path)</code> </dt> <dd> +<p>Implements the <code>'tar'</code> filter.</p> <ul class="simple"> <li>Strip leading slashes (<code>/</code> and <a class="reference internal" href="os#os.sep" title="os.sep"><code>os.sep</code></a>) from filenames.</li> <li> +<a class="reference internal" href="#tarfile-extraction-refuse"><span class="std std-ref">Refuse</span></a> to extract files with absolute paths (in case the name is absolute even after stripping slashes, e.g. <code>C:/foo</code> on Windows). This raises <a class="reference internal" href="#tarfile.AbsolutePathError" title="tarfile.AbsolutePathError"><code>AbsolutePathError</code></a>.</li> <li> +<a class="reference internal" href="#tarfile-extraction-refuse"><span class="std std-ref">Refuse</span></a> to extract files whose absolute path (after following symlinks) would end up outside the destination. This raises <a class="reference internal" href="#tarfile.OutsideDestinationError" title="tarfile.OutsideDestinationError"><code>OutsideDestinationError</code></a>.</li> <li>Clear high mode bits (setuid, setgid, sticky) and group/other write bits (<a class="reference internal" href="stat#stat.S_IWGRP" title="stat.S_IWGRP"><code>S_IWGRP</code></a> | <a class="reference internal" href="stat#stat.S_IWOTH" title="stat.S_IWOTH"><code>S_IWOTH</code></a>).</li> </ul> <p>Return the modified <code>TarInfo</code> member.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="tarfile.data_filter"> +<code>tarfile.data_filter(member, path)</code> </dt> <dd> +<p>Implements the <code>'data'</code> filter. In addition to what <code>tar_filter</code> does:</p> <ul> <li> +<p><a class="reference internal" href="#tarfile-extraction-refuse"><span class="std std-ref">Refuse</span></a> to extract links (hard or soft) that link to absolute paths, or ones that link outside the destination.</p> <p>This raises <a class="reference internal" href="#tarfile.AbsoluteLinkError" title="tarfile.AbsoluteLinkError"><code>AbsoluteLinkError</code></a> or <a class="reference internal" href="#tarfile.LinkOutsideDestinationError" title="tarfile.LinkOutsideDestinationError"><code>LinkOutsideDestinationError</code></a>.</p> <p>Note that such files are refused even on platforms that do not support symbolic links.</p> </li> <li> +<a class="reference internal" href="#tarfile-extraction-refuse"><span class="std std-ref">Refuse</span></a> to extract device files (including pipes). This raises <a class="reference internal" href="#tarfile.SpecialFileError" title="tarfile.SpecialFileError"><code>SpecialFileError</code></a>.</li> <li> +<p>For regular files, including hard links:</p> <ul class="simple"> <li>Set the owner read and write permissions (<a class="reference internal" href="stat#stat.S_IRUSR" title="stat.S_IRUSR"><code>S_IRUSR</code></a> | <a class="reference internal" href="stat#stat.S_IWUSR" title="stat.S_IWUSR"><code>S_IWUSR</code></a>).</li> <li>Remove the group & other executable permission (<a class="reference internal" href="stat#stat.S_IXGRP" title="stat.S_IXGRP"><code>S_IXGRP</code></a> | <a class="reference internal" href="stat#stat.S_IXOTH" title="stat.S_IXOTH"><code>S_IXOTH</code></a>) if the owner doesn’t have it (<a class="reference internal" href="stat#stat.S_IXUSR" title="stat.S_IXUSR"><code>S_IXUSR</code></a>).</li> </ul> </li> <li>For other files (directories), set <code>mode</code> to <code>None</code>, so that extraction methods skip applying permission bits.</li> <li>Set user and group info (<code>uid</code>, <code>gid</code>, <code>uname</code>, <code>gname</code>) to <code>None</code>, so that extraction methods skip setting it.</li> </ul> <p>Return the modified <code>TarInfo</code> member.</p> </dd> +</dl> </section> <section id="filter-errors"> <span id="tarfile-extraction-refuse"></span><h3>Filter errors</h3> <p>When a filter refuses to extract a file, it will raise an appropriate exception, a subclass of <a class="reference internal" href="#tarfile.FilterError" title="tarfile.FilterError"><code>FilterError</code></a>. This will abort the extraction if <a class="reference internal" href="#tarfile.TarFile.errorlevel" title="tarfile.TarFile.errorlevel"><code>TarFile.errorlevel</code></a> is 1 or more. With <code>errorlevel=0</code> the error will be logged and the member will be skipped, but extraction will continue.</p> </section> <section id="hints-for-further-verification"> <h3>Hints for further verification</h3> <p>Even with <code>filter='data'</code>, <em>tarfile</em> is not suited for extracting untrusted files without prior inspection. Among other issues, the pre-defined filters do not prevent denial-of-service attacks. Users should do additional checks.</p> <p>Here is an incomplete list of things to consider:</p> <ul class="simple"> <li>Extract to a <a class="reference internal" href="tempfile#tempfile.mkdtemp" title="tempfile.mkdtemp"><code>new temporary directory</code></a> to prevent e.g. exploiting pre-existing links, and to make it easier to clean up after a failed extraction.</li> <li>When working with untrusted data, use external (e.g. OS-level) limits on disk, memory and CPU usage.</li> <li>Check filenames against an allow-list of characters (to filter out control characters, confusables, foreign path separators, etc.).</li> <li>Check that filenames have expected extensions (discouraging files that execute when you “click on them”, or extension-less files like Windows special device names).</li> <li>Limit the number of extracted files, total size of extracted data, filename length (including symlink length), and size of individual files.</li> <li>Check for files that would be shadowed on case-insensitive filesystems.</li> </ul> <p>Also note that:</p> <ul class="simple"> <li>Tar files may contain multiple versions of the same file. Later ones are expected to overwrite any earlier ones. This feature is crucial to allow updating tape archives, but can be abused maliciously.</li> <li> +<em>tarfile</em> does not protect against issues with “live” data, e.g. an attacker tinkering with the destination (or source) directory while extraction (or archiving) is in progress.</li> </ul> </section> <section id="supporting-older-python-versions"> <h3>Supporting older Python versions</h3> <p>Extraction filters were added to Python 3.12, but may be backported to older versions as security updates. To check whether the feature is available, use e.g. <code>hasattr(tarfile, 'data_filter')</code> rather than checking the Python version.</p> <p>The following examples show how to support Python versions with and without the feature. Note that setting <code>extraction_filter</code> will affect any subsequent operations.</p> <ul> <li> +<p>Fully trusted archive:</p> <pre data-language="python">my_tarfile.extraction_filter = (lambda member, path: member) +my_tarfile.extractall() +</pre> </li> <li> +<p>Use the <code>'data'</code> filter if available, but revert to Python 3.11 behavior (<code>'fully_trusted'</code>) if this feature is not available:</p> <pre data-language="python">my_tarfile.extraction_filter = getattr(tarfile, 'data_filter', + (lambda member, path: member)) +my_tarfile.extractall() +</pre> </li> <li> +<p>Use the <code>'data'</code> filter; <em>fail</em> if it is not available:</p> <pre data-language="python">my_tarfile.extractall(filter=tarfile.data_filter) +</pre> <p>or:</p> <pre data-language="python">my_tarfile.extraction_filter = tarfile.data_filter +my_tarfile.extractall() +</pre> </li> <li> +<p>Use the <code>'data'</code> filter; <em>warn</em> if it is not available:</p> <pre data-language="python">if hasattr(tarfile, 'data_filter'): + my_tarfile.extractall(filter='data') +else: + # remove this when no longer needed + warn_the_user('Extracting may be unsafe; consider updating Python') + my_tarfile.extractall() +</pre> </li> </ul> </section> <section id="stateful-extraction-filter-example"> <h3>Stateful extraction filter example</h3> <p>While <em>tarfile</em>’s extraction methods take a simple <em>filter</em> callable, custom filters may be more complex objects with an internal state. It may be useful to write these as context managers, to be used like this:</p> <pre data-language="python">with StatefulFilter() as filter_func: + tar.extractall(path, filter=filter_func) +</pre> <p>Such a filter can be written as, for example:</p> <pre data-language="python">class StatefulFilter: + def __init__(self): + self.file_count = 0 + + def __enter__(self): + return self + + def __call__(self, member, path): + self.file_count += 1 + return member + + def __exit__(self, *exc_info): + print(f'{self.file_count} files extracted') +</pre> </section> </section> <section id="command-line-interface"> <span id="tarfile-commandline"></span><h2>Command-Line Interface</h2> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.4.</span></p> </div> <p>The <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module provides a simple command-line interface to interact with tar archives.</p> <p>If you want to create a new tar archive, specify its name after the <a class="reference internal" href="#cmdoption-tarfile-c"><code>-c</code></a> option and then list the filename(s) that should be included:</p> <pre data-language="shell">$ python -m tarfile -c monty.tar spam.txt eggs.txt +</pre> <p>Passing a directory is also acceptable:</p> <pre data-language="shell">$ python -m tarfile -c monty.tar life-of-brian_1979/ +</pre> <p>If you want to extract a tar archive into the current directory, use the <a class="reference internal" href="#cmdoption-tarfile-e"><code>-e</code></a> option:</p> <pre data-language="shell">$ python -m tarfile -e monty.tar +</pre> <p>You can also extract a tar archive into a different directory by passing the directory’s name:</p> <pre data-language="shell">$ python -m tarfile -e monty.tar other-dir/ +</pre> <p>For a list of the files in a tar archive, use the <a class="reference internal" href="#cmdoption-tarfile-l"><code>-l</code></a> option:</p> <pre data-language="shell">$ python -m tarfile -l monty.tar +</pre> <section id="command-line-options"> <h3>Command-line options</h3> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-l"> +<code>-l <tarfile></code> </dt> <dt class="sig sig-object std" id="cmdoption-tarfile-list"> +<code>--list <tarfile></code> </dt> <dd> +<p>List files in a tarfile.</p> </dd> +</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-c"> +<code>-c <tarfile> <source1> ... <sourceN></code> </dt> <dt class="sig sig-object std" id="cmdoption-tarfile-create"> +<code>--create <tarfile> <source1> ... <sourceN></code> </dt> <dd> +<p>Create tarfile from source files.</p> </dd> +</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-e"> +<code>-e <tarfile> [<output_dir>]</code> </dt> <dt class="sig sig-object std" id="cmdoption-tarfile-extract"> +<code>--extract <tarfile> [<output_dir>]</code> </dt> <dd> +<p>Extract tarfile into the current directory if <em>output_dir</em> is not specified.</p> </dd> +</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-t"> +<code>-t <tarfile></code> </dt> <dt class="sig sig-object std" id="cmdoption-tarfile-test"> +<code>--test <tarfile></code> </dt> <dd> +<p>Test whether the tarfile is valid or not.</p> </dd> +</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-v"> +<code>-v, --verbose</code> </dt> <dd> +<p>Verbose output.</p> </dd> +</dl> <dl class="std option"> <dt class="sig sig-object std" id="cmdoption-tarfile-filter"> +<code>--filter <filtername></code> </dt> <dd> +<p>Specifies the <em>filter</em> for <code>--extract</code>. See <a class="reference internal" href="#tarfile-extraction-filter"><span class="std std-ref">Extraction filters</span></a> for details. Only string names are accepted (that is, <code>fully_trusted</code>, <code>tar</code>, and <code>data</code>).</p> </dd> +</dl> </section> </section> <section id="examples"> <span id="tar-examples"></span><h2>Examples</h2> <p>How to extract an entire tar archive to the current working directory:</p> <pre data-language="python">import tarfile +tar = tarfile.open("sample.tar.gz") +tar.extractall(filter='data') +tar.close() +</pre> <p>How to extract a subset of a tar archive with <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code>TarFile.extractall()</code></a> using a generator function instead of a list:</p> <pre data-language="python">import os +import tarfile + +def py_files(members): + for tarinfo in members: + if os.path.splitext(tarinfo.name)[1] == ".py": + yield tarinfo + +tar = tarfile.open("sample.tar.gz") +tar.extractall(members=py_files(tar)) +tar.close() +</pre> <p>How to create an uncompressed tar archive from a list of filenames:</p> <pre data-language="python">import tarfile +tar = tarfile.open("sample.tar", "w") +for name in ["foo", "bar", "quux"]: + tar.add(name) +tar.close() +</pre> <p>The same example using the <a class="reference internal" href="../reference/compound_stmts#with"><code>with</code></a> statement:</p> <pre data-language="python">import tarfile +with tarfile.open("sample.tar", "w") as tar: + for name in ["foo", "bar", "quux"]: + tar.add(name) +</pre> <p>How to read a gzip compressed tar archive and display some member information:</p> <pre data-language="python">import tarfile +tar = tarfile.open("sample.tar.gz", "r:gz") +for tarinfo in tar: + print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="") + if tarinfo.isreg(): + print("a regular file.") + elif tarinfo.isdir(): + print("a directory.") + else: + print("something else.") +tar.close() +</pre> <p>How to create an archive and reset the user information using the <em>filter</em> parameter in <a class="reference internal" href="#tarfile.TarFile.add" title="tarfile.TarFile.add"><code>TarFile.add()</code></a>:</p> <pre data-language="python">import tarfile +def reset(tarinfo): + tarinfo.uid = tarinfo.gid = 0 + tarinfo.uname = tarinfo.gname = "root" + return tarinfo +tar = tarfile.open("sample.tar.gz", "w:gz") +tar.add("foo", filter=reset) +tar.close() +</pre> </section> <section id="supported-tar-formats"> <span id="tar-formats"></span><h2>Supported tar formats</h2> <p>There are three tar formats that can be created with the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> module:</p> <ul> <li>The POSIX.1-1988 ustar format (<a class="reference internal" href="#tarfile.USTAR_FORMAT" title="tarfile.USTAR_FORMAT"><code>USTAR_FORMAT</code></a>). 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.</li> <li>The GNU tar format (<a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code>GNU_FORMAT</code></a>). It supports long filenames and linknames, files bigger than 8 GiB and sparse files. It is the de facto standard on GNU/Linux systems. <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> fully supports the GNU tar extensions for long names, sparse file support is read-only.</li> <li> +<p>The POSIX.1-2001 pax format (<a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a>). 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. Modern tar implementations, including GNU tar, bsdtar/libarchive and star, fully support extended <em>pax</em> features; some old or unmaintained libraries may not, but should treat <em>pax</em> archives as if they were in the universally supported <em>ustar</em> format. It is the current default format for new archives.</p> <p>It extends the existing <em>ustar</em> format with 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 <em>UTF-8</em> for portability reasons.</p> </li> </ul> <p>There are some more variants of the tar format which can be read, but not created:</p> <ul class="simple"> <li>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.</li> <li>The SunOS tar extended format. This format is a variant of the POSIX.1-2001 pax format, but is not compatible.</li> </ul> </section> <section id="unicode-issues"> <span id="tar-unicode"></span><h2>Unicode issues</h2> <p>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 <em>UTF-8</em> system cannot be read correctly on a <em>Latin-1</em> system if it contains non-<em>ASCII</em> 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 <em>UTF-8</em>.</p> <p>The details of character conversion in <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code>tarfile</code></a> are controlled by the <em>encoding</em> and <em>errors</em> keyword arguments of the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code>TarFile</code></a> class.</p> <p><em>encoding</em> defines the character encoding to use for the metadata in the archive. The default value is <a class="reference internal" href="sys#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code>sys.getfilesystemencoding()</code></a> or <code>'ascii'</code> as a fallback. Depending on whether the archive is read or written, the metadata must be either decoded or encoded. If <em>encoding</em> is not set appropriately, this conversion may fail.</p> <p>The <em>errors</em> argument defines how characters are treated that cannot be converted. Possible values are listed in section <a class="reference internal" href="codecs#error-handlers"><span class="std std-ref">Error Handlers</span></a>. The default scheme is <code>'surrogateescape'</code> which Python also uses for its file system calls, see <a class="reference internal" href="os#os-filenames"><span class="std std-ref">File Names, Command Line Arguments, and Environment Variables</span></a>.</p> <p>For <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code>PAX_FORMAT</code></a> archives (the default), <em>encoding</em> is generally not needed because all the metadata is stored using <em>UTF-8</em>. <em>encoding</em> is only used in the rare cases when binary pax headers are decoded or when strings with surrogate characters are stored.</p> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/library/tarfile.html" class="_attribution-link">https://docs.python.org/3.12/library/tarfile.html</a> + </p> +</div> |
