“Python/docs/3.9/library/tarfile”的版本间差异

来自菜鸟教程
Python/docs/3.9/library/tarfile
跳转至:导航、​搜索
(autoload)
 
(Page commit)
 
第1行: 第1行:
 +
{{DISPLAYTITLE:tarfile — 读写 tar 归档文件 — Python 文档}}
 
<div id="module-tarfile" class="section">
 
<div id="module-tarfile" class="section">
  
 
<span id="tarfile-read-and-write-tar-archive-files"></span>
 
<span id="tarfile-read-and-write-tar-archive-files"></span>
= [[#module-tarfile|<code>tarfile</code>]] --- Read and write tar archive files =
+
= tarfile — 读写 tar 归档文件 =
  
'''Source code:''' [https://github.com/python/cpython/tree/3.9/Lib/tarfile.py Lib/tarfile.py]
+
'''源代码:''' [[#id1|<span id="id2" class="problematic">:source:`Lib/tarfile.py`</span>]]
  
The [[#module-tarfile|<code>tarfile</code>]] module makes it possible to read and write tar
 
archives, including those using gzip, bz2 and lzma compression.
 
Use the [[../zipfile#module-zipfile|<code>zipfile</code>]] module to read or write <code>.zip</code> files, or the
 
higher-level functions in [[../shutil#archiving-operations|<span class="std std-ref">shutil</span>]].
 
  
Some facts and figures:
+
-----
  
* reads and writes [[../gzip#module-gzip|<code>gzip</code>]], [[../bz2#module-bz2|<code>bz2</code>]] and [[../lzma#module-lzma|<code>lzma</code>]] compressed archives if the respective modules are available.
+
[[#module-tarfile|tarfile]] 模块可以读取和写入 tar 档案,包括使用 gzip、bz2 和 lzma 压缩的档案。 使用 [[../zipfile#module-zipfile|zipfile]] 模块读取或写入 <code>.zip</code> 文件,或 [[../shutil#archiving-operations|shutil]] 中的更高级别函数。
* 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.
+
* 如果相应的模块可用,则读取和写入 [[../gzip#module-gzip|gzip]]、[[../bz2#module-bz2|bz2]] [[../lzma#module-lzma|lzma]] 压缩档案。
 +
* POSIX.1-1988 (ustar) 格式的读/写支持。
 +
* GNU tar 格式的读/写支持,包括 ''longname'' ''longlink'' 扩展,只读支持 ''sparse'' 扩展的所有变体,包括稀疏文件的恢复。
 +
* POSIX.1-2001 (pax) 格式的读/写支持。
 +
* 处理目录、常规文件、硬链接、符号链接、fifos、字符设备和块设备,并能够获取和恢复文件信息,如时间戳、访问权限和所有者。
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<span class="versionmodified changed">3.3 版更改: </span>Added support for [[../lzma#module-lzma|<code>lzma</code>]] compression.
+
<span class="versionmodified changed"> 3.3 版更改: </span> 添加了对 [[../lzma#module-lzma|lzma]] 压缩的支持。
  
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt><code>tarfile.</code><code>open</code><span class="sig-paren">(</span>''name=None'', ''mode='r''', ''fileobj=None'', ''bufsize=10240'', ''\*\*kwargs''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">open</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'r'</span></span>'', ''<span class="n"><span class="pre">fileobj</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">bufsize</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">10240</span></span>'', ''<span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a [[#tarfile.TarFile|<code>TarFile</code>]] object for the pathname ''name''. For detailed
+
<dd><p>为路径名 ''name'' 返回一个 [[#tarfile.TarFile|TarFile]] 对象。 有关 [[#tarfile.TarFile|TarFile]] 对象和允许的关键字参数的详细信息,请参阅 [[#tarfile-objects|TarFile 对象]] </p>
information on [[#tarfile.TarFile|<code>TarFile</code>]] objects and the keyword arguments that are
+
<p>''mode'' 必须是 <code>'filemode[:compression]'</code> 形式的字符串,默认为 <code>'r'</code>。 以下是模式组合的完整列表:</p>
allowed, see [[#tarfile-objects|<span class="std std-ref">TarFile Objects</span>]].</p>
 
<p>''mode'' 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>
 
 
{|
 
{|
!width="28%"| <p>mode</p>
+
!width="28%"| <p>模式</p>
!width="71%"| <p>action</p>
+
!width="71%"| <p>行动</p>
 
|-
 
|-
 
| <p><code>'r' or 'r:*'</code></p>
 
| <p><code>'r' or 'r:*'</code></p>
| <p>Open for reading with transparent
+
| <p>使用透明压缩打开阅读(推荐)。</p>
compression (recommended).</p>
 
 
|-
 
|-
 
| <p><code>'r:'</code></p>
 
| <p><code>'r:'</code></p>
| <p>Open for reading exclusively without
+
| <p>开放阅读,无需压缩。</p>
compression.</p>
 
 
|-
 
|-
 
| <p><code>'r:gz'</code></p>
 
| <p><code>'r:gz'</code></p>
| <p>Open for reading with gzip compression.</p>
+
| <p>使用 gzip 压缩打开以供阅读。</p>
 
|-
 
|-
 
| <p><code>'r:bz2'</code></p>
 
| <p><code>'r:bz2'</code></p>
| <p>Open for reading with bzip2 compression.</p>
+
| <p>使用 bzip2 压缩打开以供阅读。</p>
 
|-
 
|-
 
| <p><code>'r:xz'</code></p>
 
| <p><code>'r:xz'</code></p>
| <p>Open for reading with lzma compression.</p>
+
| <p>使用 lzma 压缩打开阅读。</p>
 
|-
 
|-
| <p><code>'x'</code> or
+
| <p><code>'x'</code> <code>'x:'</code></p>
<code>'x:'</code></p>
+
| <p>创建一个不压缩的 tarfile。 如果已存在,则引发 [[../exceptions#FileExistsError|FileExistsError]] 异常。</p>
| <p>Create a tarfile exclusively without
 
compression.
 
Raise an [[../exceptions#FileExistsError|<code>FileExistsError</code>]] exception
 
if it already exists.</p>
 
 
|-
 
|-
 
| <p><code>'x:gz'</code></p>
 
| <p><code>'x:gz'</code></p>
| <p>Create a tarfile with gzip compression.
+
| <p>使用 gzip 压缩创建一个 tarfile。 如果已存在,则引发 [[../exceptions#FileExistsError|FileExistsError]] 异常。</p>
Raise an [[../exceptions#FileExistsError|<code>FileExistsError</code>]] exception
 
if it already exists.</p>
 
 
|-
 
|-
 
| <p><code>'x:bz2'</code></p>
 
| <p><code>'x:bz2'</code></p>
| <p>Create a tarfile with bzip2 compression.
+
| <p>使用 bzip2 压缩创建一个 tarfile。 如果已存在,则引发 [[../exceptions#FileExistsError|FileExistsError]] 异常。</p>
Raise an [[../exceptions#FileExistsError|<code>FileExistsError</code>]] exception
 
if it already exists.</p>
 
 
|-
 
|-
 
| <p><code>'x:xz'</code></p>
 
| <p><code>'x:xz'</code></p>
| <p>Create a tarfile with lzma compression.
+
| <p>使用 lzma 压缩创建一个 tarfile。 如果已存在,则引发 [[../exceptions#FileExistsError|FileExistsError]] 异常。</p>
Raise an [[../exceptions#FileExistsError|<code>FileExistsError</code>]] exception
 
if it already exists.</p>
 
 
|-
 
|-
 
| <p><code>'a' or 'a:'</code></p>
 
| <p><code>'a' or 'a:'</code></p>
| <p>Open for appending with no compression. The
+
| <p>打开以追加,无压缩。 如果文件不存在,则创建该文件。</p>
file is created if it does not exist.</p>
 
 
|-
 
|-
 
| <p><code>'w' or 'w:'</code></p>
 
| <p><code>'w' or 'w:'</code></p>
| <p>Open for uncompressed writing.</p>
+
| <p>打开无压缩写入。</p>
 
|-
 
|-
 
| <p><code>'w:gz'</code></p>
 
| <p><code>'w:gz'</code></p>
| <p>Open for gzip compressed writing.</p>
+
| <p>打开 gzip 压缩写入。</p>
 
|-
 
|-
 
| <p><code>'w:bz2'</code></p>
 
| <p><code>'w:bz2'</code></p>
| <p>Open for bzip2 compressed writing.</p>
+
| <p>bzip2 压缩写入打开。</p>
 
|-
 
|-
 
| <p><code>'w:xz'</code></p>
 
| <p><code>'w:xz'</code></p>
| <p>Open for lzma compressed writing.</p>
+
| <p>打开 lzma 压缩写入。</p>
 
|}
 
|}
  
<p>Note that <code>'a:gz'</code>, <code>'a:bz2'</code> or <code>'a:xz'</code> is not possible. If ''mode''
+
<p>请注意,<code>'a:gz'</code><code>'a:bz2'</code> <code>'a:xz'</code> 是不可能的。 如果 ''mode'' 不适合打开某个(压缩)文件进行读取,则会引发 [[#tarfile.ReadError|ReadError]]。 使用 ''mode'' <code>'r'</code> 来避免这种情况。 如果不支持压缩方法,则会引发 [[#tarfile.CompressionError|CompressionError]]</p>
is not suitable to open a certain (compressed) file for reading,
+
<p>如果指定了 ''fileobj'',它被用作 ''name'' 以二进制模式打开的 [[../../glossary#term-file-object|文件对象]] 的替代。 它应该在位置 0。</p>
[[#tarfile.ReadError|<code>ReadError</code>]] is raised. Use ''mode'' <code>'r'</code> to avoid this. If a
+
<p>对于模式 <code>'w:gz'</code><code>'r:gz'</code><code>'w:bz2'</code><code>'r:bz2'</code><code>'x:gz'</code><code>'x:bz2'</code>[[#tarfile.open|tarfile.open ()]] 接受关键字参数 ''compresslevel''(默认 <code>9</code>)来指定文件的压缩级别。</p>
compression method is not supported, [[#tarfile.CompressionError|<code>CompressionError</code>]] is raised.</p>
+
<p>对于模式 <code>'w:xz'</code> 和 <code>'x:xz'</code>,[[#tarfile.open|tarfile.open()]] 接受关键字参数 ''preset'' 来指定文件的压缩级别。</p>
<p>If ''fileobj'' is specified, it is used as an alternative to a [[../../glossary#term-file-object|<span class="xref std std-term">file object</span>]]
+
<p>出于特殊目的,''模式''还有第二种格式:<code>'filemode|[compression]'</code>[[#tarfile.open|tarfile.open()]] 将返回一个 [[#tarfile.TarFile|TarFile]] 对象,该对象将其数据作为块流处理。 不会对文件进行随机搜索。 如果给定,''fileobj'' 可以是任何具有 <code>read()</code> <code>write()</code> 方法的对象(取决于 ''mode'')。 ''bufsize'' 指定块大小,默认为 <code>20 * 512</code> 字节。 将此变体与例如结合使用 <code>sys.stdin</code>、套接字 [[../../glossary#term-file-object|文件对象]] 或磁带设备。 然而,这样的 [[#tarfile.TarFile|TarFile]] 对象受到限制,因为它不允许随机访问,请参阅 [[#tar-examples|示例]] 。 当前可能的模式:</p>
opened in binary mode for ''name''. It is supposed to be at position 0.</p>
 
<p>For modes <code>'w:gz'</code>, <code>'r:gz'</code>, <code>'w:bz2'</code>, <code>'r:bz2'</code>, <code>'x:gz'</code>,
 
<code>'x:bz2'</code>, [[#tarfile.open|<code>tarfile.open()</code>]] accepts the keyword argument
 
''compresslevel'' (default <code>9</code>) to specify the compression level of the file.</p>
 
<p>For special purposes, there is a second format for ''mode'':
 
<code>'filemode|[compression]'</code>. [[#tarfile.open|<code>tarfile.open()</code>]] will return a [[#tarfile.TarFile|<code>TarFile</code>]]
 
object that processes its data as a stream of blocks. No random seeking will
 
be done on the file. If given, ''fileobj'' may be any object that has a
 
<code>read()</code> or <code>write()</code> method (depending on the ''mode''). ''bufsize''
 
specifies the blocksize and defaults to <code>20 * 512</code> bytes. Use this variant
 
in combination with e.g. <code>sys.stdin</code>, a socket [[../../glossary#term-file-object|<span class="xref std std-term">file object</span>]] or a tape
 
device. However, such a [[#tarfile.TarFile|<code>TarFile</code>]] object is limited in that it does
 
not allow random access, see [[#tar-examples|<span class="std std-ref">Examples</span>]]. The currently
 
possible modes:</p>
 
 
{|
 
{|
!width="23%"| <p>Mode</p>
+
!width="23%"| <p>模式</p>
!width="77%"| <p>Action</p>
+
!width="77%"| <p>行动</p>
 
|-
 
|-
 
| <p><code>'r|*'</code></p>
 
| <p><code>'r|*'</code></p>
| <p>Open a ''stream'' of tar blocks for reading
+
| <p>打开 tar 块的 '''' 以使用透明压缩进行读取。</p>
with transparent compression.</p>
 
 
|-
 
|-
 
| <p><code>'r|'</code></p>
 
| <p><code>'r|'</code></p>
| <p>Open a ''stream'' of uncompressed tar blocks
+
| <p>打开未压缩的 tar 块的 '''' 以进行读取。</p>
for reading.</p>
 
 
|-
 
|-
 
| <p><code>'r|gz'</code></p>
 
| <p><code>'r|gz'</code></p>
| <p>Open a gzip compressed ''stream'' for
+
| <p>打开 gzip 压缩的 ''stream'' 进行阅读。</p>
reading.</p>
 
 
|-
 
|-
 
| <p><code>'r|bz2'</code></p>
 
| <p><code>'r|bz2'</code></p>
| <p>Open a bzip2 compressed ''stream'' for
+
| <p>打开一个 bzip2 压缩的 ''stream'' 进行读取。</p>
reading.</p>
 
 
|-
 
|-
 
| <p><code>'r|xz'</code></p>
 
| <p><code>'r|xz'</code></p>
| <p>Open an lzma compressed ''stream'' for
+
| <p>打开一个 lzma 压缩的 ''stream'' 进行读取。</p>
reading.</p>
 
 
|-
 
|-
 
| <p><code>'w|'</code></p>
 
| <p><code>'w|'</code></p>
| <p>Open an uncompressed ''stream'' for writing.</p>
+
| <p>打开未压缩的 '''' 进行写入。</p>
 
|-
 
|-
 
| <p><code>'w|gz'</code></p>
 
| <p><code>'w|gz'</code></p>
| <p>Open a gzip compressed ''stream'' for
+
| <p>打开一个 gzip 压缩的 ''stream'' 进行写入。</p>
writing.</p>
 
 
|-
 
|-
 
| <p><code>'w|bz2'</code></p>
 
| <p><code>'w|bz2'</code></p>
| <p>Open a bzip2 compressed ''stream'' for
+
| <p>打开一个 bzip2 压缩的 ''stream'' 进行写入。</p>
writing.</p>
 
 
|-
 
|-
 
| <p><code>'w|xz'</code></p>
 
| <p><code>'w|xz'</code></p>
| <p>Open an lzma compressed ''stream'' for
+
| <p>打开一个 lzma 压缩的 ''stream'' 进行写入。</p>
writing.</p>
 
 
|}
 
|}
  
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>The <code>'x'</code> (exclusive creation) mode was added.</p>
+
<p><span class="versionmodified changed">3.5版本变更:</span>增加了<code>'x'</code>(独创)模式。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>The ''name'' parameter accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> ''name'' 参数接受 [[../../glossary#term-path-like-object|类路径对象]] </p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; ''class'' <code>tarfile.</code><code>TarFile</code>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">TarFile</span></span>
: Class for reading and writing tar archives. Do not use this class directly: use [[#tarfile.open|<code>tarfile.open()</code>]] instead. See [[#tarfile-objects|<span class="std std-ref">TarFile Objects</span>]].
+
: 用于读取和写入 tar 档案的类。 不要直接使用这个类:使用 [[#tarfile.open|tarfile.open()]] 代替。 参见 [[#tarfile-objects|TarFile 对象]]
  
 
<dl>
 
<dl>
<dt><code>tarfile.</code><code>is_tarfile</code><span class="sig-paren">(</span>''<span class="n">name</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">is_tarfile</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return [[../constants#True|<code>True</code>]] if ''name'' is a tar archive file, that the [[#module-tarfile|<code>tarfile</code>]]
+
<dd><p>如果 ''name'' 是 tar 存档文件,则返回 [[../constants#True|True]][[#module-tarfile|tarfile]] 模块可以读取该文件。 ''name'' 可以是 [[../stdtypes#str|str]]、文件或类似文件的对象。</p>
module can read. ''name'' may be a [[../stdtypes#str|<code>str</code>]], file, or file-like object.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.9 版更改: </span>Support for file and file-like objects.</p>
+
<p><span class="versionmodified changed"> 3.9 版更改: </span> 支持文件和类文件对象。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
The [[#module-tarfile|<code>tarfile</code>]] module defines the following exceptions:
+
[[#module-tarfile|tarfile]] 模块定义了以下异常:
  
; ''exception'' <code>tarfile.</code><code>TarError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">TarError</span></span>
: Base class for all [[#module-tarfile|<code>tarfile</code>]] exceptions.
+
: 所有 [[#module-tarfile|tarfile]] 异常的基类。
  
; ''exception'' <code>tarfile.</code><code>ReadError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">ReadError</span></span>
: Is raised when a tar archive is opened, that either cannot be handled by the [[#module-tarfile|<code>tarfile</code>]] module or is somehow invalid.
+
: 在打开 tar 存档时引发,[[#module-tarfile|tarfile]] 模块无法处理或以某种方式无效。
  
; ''exception'' <code>tarfile.</code><code>CompressionError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">CompressionError</span></span>
: Is raised when a compression method is not supported or when the data cannot be decoded properly.
+
: 当不支持压缩方法或无法正确解码数据时引发。
  
; ''exception'' <code>tarfile.</code><code>StreamError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">StreamError</span></span>
: Is raised for the limitations that are typical for stream-like [[#tarfile.TarFile|<code>TarFile</code>]] objects.
+
: 由于流类 [[#tarfile.TarFile|TarFile]] 对象的典型限制而引发。
  
; ''exception'' <code>tarfile.</code><code>ExtractError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">ExtractError</span></span>
: Is raised for ''non-fatal'' errors when using [[#tarfile.TarFile.extract|<code>TarFile.extract()</code>]], but only if <code>TarFile.errorlevel</code><code>== 2</code>.
+
: 使用 [[#tarfile.TarFile.extract|TarFile.extract()]] 时,针对 ''非致命'' 错误引发,但仅在 <code>TarFile.errorlevel</code><code>== 2</code> 时引发。
  
; ''exception'' <code>tarfile.</code><code>HeaderError</code>
+
; ''<span class="pre">exception</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">HeaderError</span></span>
: Is raised by [[#tarfile.TarInfo.frombuf|<code>TarInfo.frombuf()</code>]] if the buffer it gets is invalid.
+
: 如果它获得的缓冲区无效,则由 [[#tarfile.TarInfo.frombuf|TarInfo.frombuf()]] 引发。
  
The following constants are available at the module level:
+
以下常量在模块级别可用:
  
; <code>tarfile.</code><code>ENCODING</code>
+
; <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">ENCODING</span></span>
: The default character encoding: <code>'utf-8'</code> on Windows, the value returned by [[../sys#sys|<code>sys.getfilesystemencoding()</code>]] otherwise.
+
: 默认字符编码:Windows 上的 <code>'utf-8'</code>,否则为 [[../sys#sys|sys.getfilesystemencoding()]] 返回的值。
  
Each of the following constants defines a tar archive format that the
+
以下每个常量定义了 [[#module-tarfile|tarfile]] 模块能够创建的 tar 存档格式。 有关详细信息,请参阅 [[#tar-formats|支持的 tar 格式]] 部分。
[[#module-tarfile|<code>tarfile</code>]] module is able to create. See section [[#tar-formats|<span class="std std-ref">Supported tar formats</span>]] for
 
details.
 
  
; <code>tarfile.</code><code>USTAR_FORMAT</code>
+
; <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">USTAR_FORMAT</span></span>
: POSIX.1-1988 (ustar) format.
+
: POSIX.1-1988 (ustar) 格式。
  
; <code>tarfile.</code><code>GNU_FORMAT</code>
+
; <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">GNU_FORMAT</span></span>
: GNU tar format.
+
: GNU tar 格式。
  
; <code>tarfile.</code><code>PAX_FORMAT</code>
+
; <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">PAX_FORMAT</span></span>
: POSIX.1-2001 (pax) format.
+
: POSIX.1-2001 (pax) 格式。
  
 
<dl>
 
<dl>
<dt><code>tarfile.</code><code>DEFAULT_FORMAT</code></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">DEFAULT_FORMAT</span></span></dt>
<dd><p>The default format for creating archives. This is currently [[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]].</p>
+
<dd><p>创建档案的默认格式。 目前是 [[#tarfile.PAX_FORMAT|PAX_FORMAT]]</p>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.8 版更改: </span>The default format for new archives was changed to
+
<p><span class="versionmodified changed"> 3.8 版更改: </span> 新存档的默认格式从 [[#tarfile.GNU_FORMAT|GNU_FORMAT]] 更改为 [[#tarfile.PAX_FORMAT|PAX_FORMAT]]</p>
[[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]] from [[#tarfile.GNU_FORMAT|<code>GNU_FORMAT</code>]].</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
第225行: 第184行:
 
<div class="admonition seealso">
 
<div class="admonition seealso">
  
参见
+
也可以看看
  
; Module [[../zipfile#module-zipfile|<code>zipfile</code>]]
+
; 模块 [[../zipfile#module-zipfile|zipfile]]
: Documentation of the [[../zipfile#module-zipfile|<code>zipfile</code>]] standard module.
+
: [[../zipfile#module-zipfile|zipfile]] 标准模块的文档。
; [[../shutil#archiving-operations|<span class="std std-ref">Archiving operations</span>]]
+
; [[../shutil#archiving-operations|<span class="std std-ref">归档操作</span>]]
: Documentation of the higher-level archiving facilities provided by the standard [[../shutil#module-shutil|<code>shutil</code>]] module.
+
: 标准 [[../shutil#module-shutil|shutil]] 模块提供的更高级别归档工具的文档。
; [https://www.gnu.org/software/tar/manual/html_node/Standard.html GNU tar manual, Basic Tar Format]
+
; [https://www.gnu.org/software/tar/manual/html_node/Standard.html GNU tar 手册,基本 Tar 格式]
: Documentation for tar archive files, including GNU tar extensions.
+
: tar 存档文件的文档,包括 GNU tar 扩展。
  
  
第238行: 第197行:
 
<div id="tarfile-objects" class="section">
 
<div id="tarfile-objects" class="section">
  
<span id="id1"></span>
+
<span id="id3"></span>
== TarFile Objects ==
+
== TarFile 对象 ==
  
The [[#tarfile.TarFile|<code>TarFile</code>]] object provides an interface to a tar archive. A tar
+
[[#tarfile.TarFile|TarFile]] 对象提供了一个 tar 存档的接口。 tar 档案是一个块序列。 归档成员(存储的文件)由头块和数据块组成。 可以将文件多次存储在 tar 存档中。 每个存档成员都由一个 [[#tarfile.TarInfo|TarInfo]] 对象表示,有关详细信息,请参阅 [[#tarinfo-objects|TarInfo 对象]]
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 [[#tarfile.TarInfo|<code>TarInfo</code>]]
 
object, see [[#tarinfo-objects|<span class="std std-ref">TarInfo Objects</span>]] for details.
 
  
A [[#tarfile.TarFile|<code>TarFile</code>]] object can be used as a context manager in a [[../../reference/compound_stmts#with|<code>with</code>]]
+
[[#tarfile.TarFile|TarFile]] 对象可以用作 [[../../reference/compound_stmts#with|with]] 语句中的上下文管理器。 当块完成时它会自动关闭。 请注意,如果出现异常情况,为写入而打开的存档将不会被最终确定; 只有内部使用的文件对象将被关闭。 有关用例,请参阅 [[#tar-examples|示例]] 部分。
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
 
[[#tar-examples|<span class="std std-ref">Examples</span>]] section for a use case.
 
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.2 新版功能: </span>Added support for the context management protocol.
+
<span class="versionmodified added"> 3.2 新功能: </span> 增加了对上下文管理协议的支持。
  
  
 
</div>
 
</div>
 
<dl>
 
<dl>
<dt>''class'' <code>tarfile.</code><code>TarFile</code><span class="sig-paren">(</span>''<span class="n">name</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">mode</span><span class="o">=</span><span class="default_value">'r'</span>'', ''<span class="n">fileobj</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">format</span><span class="o">=</span><span class="default_value">DEFAULT_FORMAT</span>'', ''<span class="n">tarinfo</span><span class="o">=</span><span class="default_value">TarInfo</span>'', ''<span class="n">dereference</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">ignore_zeros</span><span class="o">=</span><span class="default_value">False</span>'', ''<span class="n">encoding</span><span class="o">=</span><span class="default_value">ENCODING</span>'', ''<span class="n">errors</span><span class="o">=</span><span class="default_value">'surrogateescape'</span>'', ''<span class="n">pax_headers</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">debug</span><span class="o">=</span><span class="default_value">0</span>'', ''<span class="n">errorlevel</span><span class="o">=</span><span class="default_value">0</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">TarFile</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'r'</span></span>'', ''<span class="n"><span class="pre">fileobj</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">format</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">DEFAULT_FORMAT</span></span>'', ''<span class="n"><span class="pre">tarinfo</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">TarInfo</span></span>'', ''<span class="n"><span class="pre">dereference</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">ignore_zeros</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>'', ''<span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ENCODING</span></span>'', ''<span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'surrogateescape'</span></span>'', ''<span class="n"><span class="pre">pax_headers</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">debug</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span>'', ''<span class="n"><span class="pre">errorlevel</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>All following arguments are optional and can be accessed as instance attributes
+
<dd><p>以下所有参数都是可选的,也可以作为实例属性访问。</p>
as well.</p>
+
<p>''name'' 是存档的路径名。 ''name'' 可能是一个 [[../../glossary#term-path-like-object|类似路径的对象]] 。 如果给出 ''fileobj'',则可以省略。 在这种情况下,如果存在文件对象的 <code>name</code> 属性,则使用该属性。</p>
<p>''name'' is the pathname of the archive. ''name'' may be a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].
+
<p>''mode'' <code>'r'</code> 从现有档案中读取,<code>'a'</code> 将数据附加到现有文件,<code>'w'</code> 创建一个覆盖现有文件的新文件一个,或 <code>'x'</code> 仅在新文件不存在时创建新文件。</p>
It can be omitted if ''fileobj'' is given.
+
<p>如果给出 ''fileobj'',则用于读取或写入数据。 如果可以确定,则 ''mode'' ''fileobj'' 的模式覆盖。 ''fileobj'' 将从位置 0 开始使用。</p>
In this case, the file object's <code>name</code> attribute is used if it exists.</p>
 
<p>''mode'' 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 ''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.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>''fileobj'' is not closed, when [[#tarfile.TarFile|<code>TarFile</code>]] is closed.</p>
+
<p>''fileobj'' 不关闭,当 [[#tarfile.TarFile|TarFile]] 关闭时。</p>
  
 
</div>
 
</div>
<p>''format'' controls the archive format for writing. It must be one of the constants
+
<p>''format'' 控制写入的存档格式。 它必须是在模块级别定义的常量 [[#tarfile.USTAR_FORMAT|USTAR_FORMAT]][[#tarfile.GNU_FORMAT|GNU_FORMAT]] [[#tarfile.PAX_FORMAT|PAX_FORMAT]] 之一。 读取时,即使单个存档中存在不同的格式,也会自动检测格式。</p>
[[#tarfile.USTAR_FORMAT|<code>USTAR_FORMAT</code>]], [[#tarfile.GNU_FORMAT|<code>GNU_FORMAT</code>]] or [[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]] that are
+
<p>''tarinfo'' 参数可用于用不同的类替换默认的 [[#tarfile.TarInfo|TarInfo]] 类。</p>
defined at module level. When reading, format will be automatically detected, even
+
<p>如果 ''dereference'' [[../constants#False|False]],则将符号链接和硬链接添加到存档。 如果是[[../constants#True|True]],则将目标文件的内容添加到存档中。 这对不支持符号链接的系统没有影响。</p>
if different formats are present in a single archive.</p>
+
<p>如果 ''ignore_zeros'' [[../constants#False|False]],则将空块视为存档的结尾。 如果是 [[../constants#True|True]],则跳过空(和无效)块并尝试获取尽可能多的成员。 这仅对读取连接或损坏的档案有用。</p>
<p>The ''tarinfo'' argument can be used to replace the default [[#tarfile.TarInfo|<code>TarInfo</code>]] class
+
<p>''debug'' 可以设置为从 <code>0</code>(无调试消息)到 <code>3</code>(所有调试消息)。 消息写入 <code>sys.stderr</code></p>
with a different one.</p>
+
<p>如果 ''errorlevel'' <code>0</code>,则使用 [[#tarfile.TarFile.extract|TarFile.extract()]] 时会忽略所有错误。 然而,当启用调试时,它们在调试输出中显示为错误消息。 如果 <code>1</code>,则所有 ''fatal'' 错误都作为 [[../exceptions#OSError|OSError]] 异常引发。 如果 <code>2</code>,所有 ''非致命'' 错误也会作为 [[#tarfile.TarError|TarError]] 异常引发。</p>
<p>If ''dereference'' is [[../constants#False|<code>False</code>]], add symbolic and hard links to the archive. If it
+
<p>''encoding'' ''errors'' 参数定义了用于读取或写入存档的字符编码以及将如何处理转换错误。 默认设置适用于大多数用户。 有关详细信息,请参阅 [[#tar-unicode|Unicode 问题]] 部分。</p>
is [[../constants#True|<code>True</code>]], add the content of the target files to the archive. This has no
+
<p>''pax_headers'' 参数是一个可选的字符串字典,如果 ''format'' [[#tarfile.PAX_FORMAT|PAX_FORMAT]],它将作为 pax 全局标头添加。</p>
effect on systems that do not support symbolic links.</p>
 
<p>If ''ignore_zeros'' is [[../constants#False|<code>False</code>]], treat an empty block as the end of the archive.
 
If it is [[../constants#True|<code>True</code>]], 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>''debug'' 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>If ''errorlevel'' is <code>0</code>, all errors are ignored when using [[#tarfile.TarFile.extract|<code>TarFile.extract()</code>]].
 
Nevertheless, they appear as error messages in the debug output, when debugging
 
is enabled. If <code>1</code>, all ''fatal'' errors are raised as [[../exceptions#OSError|<code>OSError</code>]]
 
exceptions. If <code>2</code>, all ''non-fatal'' errors are raised as [[#tarfile.TarError|<code>TarError</code>]]
 
exceptions as well.</p>
 
<p>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 [[#tar-unicode|<span class="std std-ref">Unicode issues</span>]] for in-depth information.</p>
 
<p>The ''pax_headers'' argument is an optional dictionary of strings which
 
will be added as a pax global header if ''format'' is [[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]].</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>Use <code>'surrogateescape'</code> as the default for the ''errors'' argument.</p>
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 使用 <code>'surrogateescape'</code> 作为 ''errors'' 参数的默认值。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>The <code>'x'</code> (exclusive creation) mode was added.</p>
+
<p><span class="versionmodified changed">3.5版本变更:</span>增加了<code>'x'</code>(独创)模式。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>The ''name'' parameter accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> ''name'' 参数接受 [[../../glossary#term-path-like-object|类路径对象]] </p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; ''classmethod'' <code>TarFile.</code><code>open</code><span class="sig-paren">(</span>''...''<span class="sig-paren">)</span>
+
; ''<span class="pre">classmethod</span>'' <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">open</span></span><span class="sig-paren">(</span>''<span class="pre">...</span>''<span class="sig-paren">)</span>
: Alternative constructor. The [[#tarfile.open|<code>tarfile.open()</code>]] function is actually a shortcut to this classmethod.
+
: 替代构造函数。 [[#tarfile.open|tarfile.open()]] 函数实际上是这个类方法的快捷方式。
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>getmember</code><span class="sig-paren">(</span>''<span class="n">name</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">getmember</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Return a [[#tarfile.TarInfo|<code>TarInfo</code>]] object for member ''name''. If ''name'' can not be found
+
<dd><p>为成员 ''name'' 返回一个 [[#tarfile.TarInfo|TarInfo]] 对象。 如果在存档中找不到 ''name'',则会引发 [[../exceptions#KeyError|KeyError]]</p>
in the archive, [[../exceptions#KeyError|<code>KeyError</code>]] is raised.</p>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>If a member occurs more than once in the archive, its last occurrence is assumed
+
<p>如果某个成员在存档中出现多次,则假定其最后一次出现是最新版本。</p>
to be the most up-to-date version.</p>
 
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>TarFile.</code><code>getmembers</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">getmembers</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the members of the archive as a list of [[#tarfile.TarInfo|<code>TarInfo</code>]] objects. The list has the same order as the members in the archive.
+
: 将存档成员作为 [[#tarfile.TarInfo|TarInfo]] 对象列表返回。 该列表与存档中的成员具有相同的顺序。
  
; <code>TarFile.</code><code>getnames</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">getnames</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the members as a list of their names. It has the same order as the list returned by [[#tarfile.TarFile.getmembers|<code>getmembers()</code>]].
+
: 将成员作为其姓名列表返回。 它与 [[#tarfile.TarFile.getmembers|getmembers()]] 返回的列表具有相同的顺序。
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>list</code><span class="sig-paren">(</span>''<span class="n">verbose</span><span class="o">=</span><span class="default_value">True</span>'', ''<span class="o">*</span>'', ''<span class="n">members</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">list</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">verbose</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">members</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Print a table of contents to <code>sys.stdout</code>. If ''verbose'' is [[../constants#False|<code>False</code>]],
+
<dd><p>将目录打印到 <code>sys.stdout</code>。 如果 ''verbose'' [[../constants#False|False]],则仅打印成员的名称。 如果是 [[../constants#True|True]],则产生类似于 '''ls -l''' 的输出。 如果给出了可选的 ''members'',它必须是由 [[#tarfile.TarFile.getmembers|getmembers()]] 返回的列表的子集。</p>
only the names of the members are printed. If it is [[../constants#True|<code>True</code>]], output
 
similar to that of '''ls -l''' is produced. If optional ''members'' is
 
given, it must be a subset of the list returned by [[#tarfile.TarFile.getmembers|<code>getmembers()</code>]].</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added the ''members'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 增加了 ''members'' 参数。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>TarFile.</code><code>next</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">next</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return the next member of the archive as a [[#tarfile.TarInfo|<code>TarInfo</code>]] object, when [[#tarfile.TarFile|<code>TarFile</code>]] is opened for reading. Return [[../constants#None|<code>None</code>]] if there is no more available.
+
: 当打开 [[#tarfile.TarFile|TarFile]] 进行读取时,将存档的下一个成员作为 [[#tarfile.TarInfo|TarInfo]] 对象返回。 如果没有更多可用,则返回 [[../constants#None|None]]
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>extractall</code><span class="sig-paren">(</span>''<span class="n">path</span><span class="o">=</span><span class="default_value">'.'</span>'', ''<span class="n">members</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="o">*</span>'', ''<span class="n">numeric_owner</span><span class="o">=</span><span class="default_value">False</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">extractall</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">path</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'.'</span></span>'', ''<span class="n"><span class="pre">members</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">numeric_owner</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Extract all members from the archive to the current working directory or
+
<dd><p>将存档中的所有成员提取到当前工作目录或目录 ''path''。 如果给出了可选的 ''members'',它必须是由 [[#tarfile.TarFile.getmembers|getmembers()]] 返回的列表的子集。 在提取所有成员后设置目录信息,如所有者、修改时间和权限。 这样做是为了解决两个问题: 每次在其中创建文件时都会重置目录的修改时间。 而且,如果目录的权限不允许写入,则将文件提取到该目录将失败。</p>
directory ''path''. If optional ''members'' is given, it must be a subset of the
+
<p>如果 ''numeric_owner'' [[../constants#True|True]],则 tarfile 中的 uid gid 编号用于设置提取文件的所有者/组。 否则,将使用 tarfile 中的命名值。</p>
list returned by [[#tarfile.TarFile.getmembers|<code>getmembers()</code>]]. 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 ''numeric_owner'' is [[../constants#True|<code>True</code>]], 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>
 
 
<div class="admonition warning">
 
<div class="admonition warning">
  
 
<p>警告</p>
 
<p>警告</p>
<p>Never extract archives from untrusted sources without prior inspection.
+
<p>未经事先检查,切勿从不受信任的来源提取档案。 文件可能是在 ''path'' 之外创建的,例如 具有以 <code>&quot;/&quot;</code> 开头的绝对文件名或以两个点 <code>&quot;..&quot;</code> 开头的文件名的成员。</p>
It is possible that files are created outside of ''path'', e.g. members
 
that have absolute filenames starting with <code>&quot;/&quot;</code> or filenames with two
 
dots <code>&quot;..&quot;</code>.</p>
 
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added the ''numeric_owner'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 添加 ''numeric_owner'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.6 版更改: </span>The ''path'' parameter accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed">在 3.6 版更改:</span>''path'' 参数接受一个 [[../../glossary#term-path-like-object|path-like object]]</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>extract</code><span class="sig-paren">(</span>''<span class="n">member</span>'', ''<span class="n">path</span><span class="o">=</span><span class="default_value">''</span>'', ''<span class="n">set_attrs</span><span class="o">=</span><span class="default_value">True</span>'', ''<span class="o">*</span>'', ''<span class="n">numeric_owner</span><span class="o">=</span><span class="default_value">False</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">extract</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">member</span></span>'', ''<span class="n"><span class="pre">path</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span>'', ''<span class="n"><span class="pre">set_attrs</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">numeric_owner</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Extract a member from the archive to the current working directory, using its
+
<dd><p>使用其全名从存档中提取成员到当前工作目录。 尽可能准确地提取其文件信息。 ''member'' 可以是文件名或 [[#tarfile.TarInfo|TarInfo]] 对象。 您可以使用 ''path'' 指定不同的目录。 ''path'' 可能是一个 [[../../glossary#term-path-like-object|path-like object]]。 除非 ''set_attrs'' 为 false,否则设置文件属性(所有者、mtime、模式)。</p>
full name. Its file information is extracted as accurately as possible. ''member''
+
<p>如果 ''numeric_owner'' [[../constants#True|True]],则 tarfile 中的 uid gid 编号用于设置提取文件的所有者/组。 否则,将使用 tarfile 中的命名值。</p>
may be a filename or a [[#tarfile.TarInfo|<code>TarInfo</code>]] object. You can specify a different
 
directory using ''path''. ''path'' may be a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].
 
File attributes (owner, mtime, mode) are set unless ''set_attrs'' is false.</p>
 
<p>If ''numeric_owner'' is [[../constants#True|<code>True</code>]], 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>
 
 
<div class="admonition note">
 
<div class="admonition note">
  
<p>注解</p>
+
<p>笔记</p>
<p>The [[#tarfile.TarFile.extract|<code>extract()</code>]] method does not take care of several extraction issues.
+
<p>[[#tarfile.TarFile.extract|extract()]] 方法不处理几个提取问题。 在大多数情况下,您应该考虑使用 [[#tarfile.TarFile.extractall|extractall()]] 方法。</p>
In most cases you should consider using the [[#tarfile.TarFile.extractall|<code>extractall()</code>]] method.</p>
 
  
 
</div>
 
</div>
第407行: 第311行:
  
 
<p>警告</p>
 
<p>警告</p>
<p>See the warning for [[#tarfile.TarFile.extractall|<code>extractall()</code>]].</p>
+
<p>请参阅 [[#tarfile.TarFile.extractall|extractall()]] 的警告。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>Added the ''set_attrs'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 添加 ''set_attrs'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.5 版更改: </span>Added the ''numeric_owner'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.5 版更改: </span> 添加 ''numeric_owner'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">在 3.6 版更改: </span>The ''path'' parameter accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed">在 3.6 版更改:</span>''path'' 参数接受一个 [[../../glossary#term-path-like-object|path-like object]]</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>extractfile</code><span class="sig-paren">(</span>''<span class="n">member</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">extractfile</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">member</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Extract a member from the archive as a file object. ''member'' may be
+
<dd><p>从存档中提取成员作为文件对象。 ''member'' 可以是文件名或 [[#tarfile.TarInfo|TarInfo]] 对象。 如果 ''member'' 是常规文件或链接,则返回 [[../io#io|io.BufferedReader]] 对象。 对于所有其他现有成员,返回 [[../constants#None|None]]。 如果 ''member'' 未出现在存档中,则会引发 [[../exceptions#KeyError|KeyError]]</p>
a filename or a [[#tarfile.TarInfo|<code>TarInfo</code>]] object. If ''member'' is a regular file or
 
a link, an [[../io#io|<code>io.BufferedReader</code>]] object is returned. For all other
 
existing members, [[../constants#None|<code>None</code>]] is returned. If ''member'' does not appear
 
in the archive, [[../exceptions#KeyError|<code>KeyError</code>]] is raised.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.3 版更改: </span>Return an [[../io#io|<code>io.BufferedReader</code>]] object.</p>
+
<p><span class="versionmodified changed"> 3.3 版更改: </span> 返回 [[../io#io|io.BufferedReader]] 对象。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>add</code><span class="sig-paren">(</span>''<span class="n">name</span>'', ''<span class="n">arcname</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">recursive</span><span class="o">=</span><span class="default_value">True</span>'', ''<span class="o">*</span>'', ''<span class="n">filter</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">add</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span>'', ''<span class="n"><span class="pre">arcname</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">recursive</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span>'', ''<span class="o"><span class="pre">*</span></span>'', ''<span class="n"><span class="pre">filter</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Add the file ''name'' to the archive. ''name'' may be any type of file
+
<dd><p>将文件 ''name'' 添加到存档中。 ''name'' 可以是任何类型的文件(目录、fifo、符号链接等)。 如果给定,''arcname'' 指定存档中文件的替代名称。 默认情况下以递归方式添加目录。 这可以通过将 ''recursive'' 设置为 [[../constants#False|False]] 来避免。 递归按排序顺序添加条目。 如果给出 ''filter'',它应该是一个函数,它接受一个 [[#tarfile.TarInfo|TarInfo]] 对象参数并返回改变后的 [[#tarfile.TarInfo|TarInfo]] 对象。 如果它返回 [[../constants#None|None]],则 [[#tarfile.TarInfo|TarInfo]] 对象将从存档中排除。 有关示例,请参阅 [[#tar-examples|示例]] </p>
(directory, fifo, symbolic link, etc.). If given, ''arcname'' specifies an
 
alternative name for the file in the archive. Directories are added
 
recursively by default. This can be avoided by setting ''recursive'' to
 
[[../constants#False|<code>False</code>]]. Recursion adds entries in sorted order.
 
If ''filter'' is given, it
 
should be a function that takes a [[#tarfile.TarInfo|<code>TarInfo</code>]] object argument and
 
returns the changed [[#tarfile.TarInfo|<code>TarInfo</code>]] object. If it instead returns
 
[[../constants#None|<code>None</code>]] the [[#tarfile.TarInfo|<code>TarInfo</code>]] object will be excluded from the
 
archive. See [[#tar-examples|<span class="std std-ref">Examples</span>]] for an example.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>Added the ''filter'' parameter.</p>
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 添加 ''过滤器'' 参数。</p>
  
 
</div>
 
</div>
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.7 版更改: </span>Recursion adds entries in sorted order.</p>
+
<p><span class="versionmodified changed"> 3.7 版更改: </span> 递归按排序顺序添加条目。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>TarFile.</code><code>addfile</code><span class="sig-paren">(</span>''<span class="n">tarinfo</span>'', ''<span class="n">fileobj</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">addfile</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">tarinfo</span></span>'', ''<span class="n"><span class="pre">fileobj</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span>
: Add the [[#tarfile.TarInfo|<code>TarInfo</code>]] object ''tarinfo'' to the archive. If ''fileobj'' is given, it should be a [[../../glossary#term-binary-file|<span class="xref std std-term">binary file</span>]], and <code>tarinfo.size</code> bytes are read from it and added to the archive. You can create [[#tarfile.TarInfo|<code>TarInfo</code>]] objects directly, or by using [[#tarfile.TarFile.gettarinfo|<code>gettarinfo()</code>]].
+
: [[#tarfile.TarInfo|TarInfo]] 对象 ''tarinfo'' 添加到存档中。 如果给出 ''fileobj'',它应该是一个 [[../../glossary#term-binary-file|二进制文件]] ,从中读取 <code>tarinfo.size</code> 字节并添加到存档中。 您可以直接创建 [[#tarfile.TarInfo|TarInfo]] 对象,也可以使用 [[#tarfile.TarFile.gettarinfo|gettarinfo()]]
  
 
<dl>
 
<dl>
<dt><code>TarFile.</code><code>gettarinfo</code><span class="sig-paren">(</span>''<span class="n">name</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">arcname</span><span class="o">=</span><span class="default_value">None</span>'', ''<span class="n">fileobj</span><span class="o">=</span><span class="default_value">None</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">gettarinfo</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">arcname</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>'', ''<span class="n"><span class="pre">fileobj</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create a [[#tarfile.TarInfo|<code>TarInfo</code>]] object from the result of [[../os#os|<code>os.stat()</code>]] or
+
<dd><p>根据现有文件上的 [[../os#os|os.stat()]] 或等效结果创建 [[#tarfile.TarInfo|TarInfo]] 对象。 该文件要么由 ''name'' 命名,要么指定为 [[../../glossary#term-file-object|file object]] ''fileobj'' 和文件描述符。 ''name'' 可能是一个 [[../../glossary#term-path-like-object|类似路径的对象]] 。 如果给定,''arcname'' 指定存档中文件的替代名称,否则,名称取自 ''fileobj'' [[../io#io.FileIO|name]] 属性,或 '']name'' 参数。 名称应为文本字符串。</p>
equivalent on an existing file. The file is either named by ''name'', or
+
<p>在使用 [[#tarfile.TarFile.addfile|addfile()]] 添加之前,您可以修改 [[#tarfile.TarInfo|TarInfo]] 的一些属性。 如果文件对象不是位于文件开头的普通文件对象,可能需要修改[[#tarfile.TarInfo.size|size]]等属性。 对于诸如 [[../gzip#gzip|GzipFile]] 之类的对象就是这种情况。 [[#tarfile.TarInfo.name|name]] 也可以修改,在这种情况下 ''arcname'' 可能是一个虚拟字符串。</p>
specified as a [[../../glossary#term-file-object|<span class="xref std std-term">file object</span>]] ''fileobj'' with a file descriptor.
 
''name'' may be a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]]. If
 
given, ''arcname'' specifies an alternative name for the file in the
 
archive, otherwise, the name is taken from ''fileobj''’s
 
[[../io#io.FileIO|<code>name</code>]] attribute, or the ''name'' argument. The name
 
should be a text string.</p>
 
<p>You can modify
 
some of the [[#tarfile.TarInfo|<code>TarInfo</code>]]’s attributes before you add it using [[#tarfile.TarFile.addfile|<code>addfile()</code>]].
 
If the file object is not an ordinary file object positioned at the
 
beginning of the file, attributes such as [[#tarfile.TarInfo.size|<code>size</code>]] may need
 
modifying. This is the case for objects such as [[../gzip#gzip|<code>GzipFile</code>]].
 
The [[#tarfile.TarInfo.name|<code>name</code>]] may also be modified, in which case ''arcname''
 
could be a dummy string.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.6 版更改: </span>The ''name'' parameter accepts a [[../../glossary#term-path-like-object|<span class="xref std std-term">path-like object</span>]].</p>
+
<p><span class="versionmodified changed"> 3.6 版更改: </span> ''name'' 参数接受 [[../../glossary#term-path-like-object|类路径对象]] </p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
; <code>TarFile.</code><code>close</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Close the [[#tarfile.TarFile|<code>TarFile</code>]]. In write mode, two finishing zero blocks are appended to the archive.
+
: 关闭 [[#tarfile.TarFile|TarFile]]。 在写入模式下,两个完成零块被附加到存档中。
  
; <code>TarFile.</code><code>pax_headers</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarFile.</span></span><span class="sig-name descname"><span class="pre">pax_headers</span></span>
: A dictionary containing key-value pairs of pax global headers.
+
: 包含 pax 全局标头的键值对的字典。
  
  
第498行: 第376行:
 
<div id="tarinfo-objects" class="section">
 
<div id="tarinfo-objects" class="section">
  
<span id="id2"></span>
+
<span id="id4"></span>
== TarInfo Objects ==
+
== TarInfo 对象 ==
  
A [[#tarfile.TarInfo|<code>TarInfo</code>]] object represents one member in a [[#tarfile.TarFile|<code>TarFile</code>]]. Aside
+
[[#tarfile.TarInfo|TarInfo]] 对象代表 [[#tarfile.TarFile|TarFile]] 中的一个成员。 除了存储文件的所有必需属性(如文件类型、大小、时间、权限、所有者等)外,它还提供了一些有用的方法来确定其类型。 它确实 '''' 包含文件本身的数据。
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.
 
  
[[#tarfile.TarInfo|<code>TarInfo</code>]] objects are returned by [[#tarfile.TarFile|<code>TarFile</code>]]'s methods
+
[[#tarfile.TarInfo|TarInfo]] 对象由 [[#tarfile.TarFile|TarFile]] 的方法 <code>getmember()</code><code>getmembers()</code> <code>gettarinfo()</code> 返回。
<code>getmember()</code>, <code>getmembers()</code> and <code>gettarinfo()</code>.
 
  
; ''class'' <code>tarfile.</code><code>TarInfo</code><span class="sig-paren">(</span>''<span class="n">name</span><span class="o">=</span><span class="default_value">''</span>''<span class="sig-paren">)</span>
+
; ''<span class="pre">class</span>'' <span class="sig-prename descclassname"><span class="pre">tarfile.</span></span><span class="sig-name descname"><span class="pre">TarInfo</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">name</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span>''<span class="sig-paren">)</span>
: Create a [[#tarfile.TarInfo|<code>TarInfo</code>]] object.
+
: 创建一个 [[#tarfile.TarInfo|TarInfo]] 对象。
  
 
<dl>
 
<dl>
<dt>''classmethod'' <code>TarInfo.</code><code>frombuf</code><span class="sig-paren">(</span>''<span class="n">buf</span>'', ''<span class="n">encoding</span>'', ''<span class="n">errors</span>''<span class="sig-paren">)</span></dt>
+
<dt>''<span class="pre">classmethod</span>'' <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">frombuf</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">buf</span></span>'', ''<span class="n"><span class="pre">encoding</span></span>'', ''<span class="n"><span class="pre">errors</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create and return a [[#tarfile.TarInfo|<code>TarInfo</code>]] object from string buffer ''buf''.</p>
+
<dd><p>从字符串缓冲区 ''buf'' 创建并返回一个 [[#tarfile.TarInfo|TarInfo]] 对象。</p>
<p>Raises [[#tarfile.HeaderError|<code>HeaderError</code>]] if the buffer is invalid.</p></dd></dl>
+
<p>如果缓冲区无效,则引发 [[#tarfile.HeaderError|HeaderError]]</p></dd></dl>
  
; ''classmethod'' <code>TarInfo.</code><code>fromtarfile</code><span class="sig-paren">(</span>''<span class="n">tarfile</span>''<span class="sig-paren">)</span>
+
; ''<span class="pre">classmethod</span>'' <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">fromtarfile</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">tarfile</span></span>''<span class="sig-paren">)</span>
: Read the next member from the [[#tarfile.TarFile|<code>TarFile</code>]] object ''tarfile'' and return it as a [[#tarfile.TarInfo|<code>TarInfo</code>]] object.
+
: [[#tarfile.TarFile|TarFile]] 对象 ''tarfile'' 读取下一个成员并将其作为 [[#tarfile.TarInfo|TarInfo]] 对象返回。
  
 
<dl>
 
<dl>
<dt><code>TarInfo.</code><code>tobuf</code><span class="sig-paren">(</span>''<span class="n">format</span><span class="o">=</span><span class="default_value">DEFAULT_FORMAT</span>'', ''<span class="n">encoding</span><span class="o">=</span><span class="default_value">ENCODING</span>'', ''<span class="n">errors</span><span class="o">=</span><span class="default_value">'surrogateescape'</span>''<span class="sig-paren">)</span></dt>
+
<dt><span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">tobuf</span></span><span class="sig-paren">(</span>''<span class="n"><span class="pre">format</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">DEFAULT_FORMAT</span></span>'', ''<span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">ENCODING</span></span>'', ''<span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'surrogateescape'</span></span>''<span class="sig-paren">)</span></dt>
<dd><p>Create a string buffer from a [[#tarfile.TarInfo|<code>TarInfo</code>]] object. For information on the
+
<dd><p>[[#tarfile.TarInfo|TarInfo]] 对象创建字符串缓冲区。 有关参数的信息,请参阅 [[#tarfile.TarFile|TarFile]] 类的构造函数。</p>
arguments see the constructor of the [[#tarfile.TarFile|<code>TarFile</code>]] class.</p>
 
 
<div class="versionchanged">
 
<div class="versionchanged">
  
<p><span class="versionmodified changed">3.2 版更改: </span>Use <code>'surrogateescape'</code> as the default for the ''errors'' argument.</p>
+
<p><span class="versionmodified changed"> 3.2 版更改: </span> 使用 <code>'surrogateescape'</code> 作为 ''errors'' 参数的默认值。</p>
  
 
</div></dd></dl>
 
</div></dd></dl>
  
A <code>TarInfo</code> object has the following public data attributes:
+
<code>TarInfo</code> 对象具有以下公共数据属性:
  
; <code>TarInfo.</code><code>name</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">name</span></span>
: Name of the archive member.
+
: 存档成员的名称。
  
; <code>TarInfo.</code><code>size</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">size</span></span>
: Size in bytes.
+
: 以字节为单位的大小。
  
; <code>TarInfo.</code><code>mtime</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">mtime</span></span>
: Time of last modification.
+
: 上次修改时间。
  
; <code>TarInfo.</code><code>mode</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">mode</span></span>
: Permission bits.
+
: 权限位。
  
; <code>TarInfo.</code><code>type</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">type</span></span>
: File type. ''type'' is usually one of these constants: <code>REGTYPE</code>, <code>AREGTYPE</code>, <code>LNKTYPE</code>, <code>SYMTYPE</code>, <code>DIRTYPE</code>, <code>FIFOTYPE</code>, <code>CONTTYPE</code>, <code>CHRTYPE</code>, <code>BLKTYPE</code>, <code>GNUTYPE_SPARSE</code>. To determine the type of a [[#tarfile.TarInfo|<code>TarInfo</code>]] object more conveniently, use the <code>is*()</code> methods below.
+
: 文件类型。 ''type'' 通常是以下常量之一:<code>REGTYPE</code><code>AREGTYPE</code><code>LNKTYPE</code><code>SYMTYPE</code><code>DIRTYPE</code>、[ X104X]、<code>CONTTYPE</code><code>CHRTYPE</code><code>BLKTYPE</code><code>GNUTYPE_SPARSE</code>。 要更方便地确定 [[#tarfile.TarInfo|TarInfo]] 对象的类型,请使用下面的 <code>is*()</code> 方法。
  
; <code>TarInfo.</code><code>linkname</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">linkname</span></span>
: Name of the target file name, which is only present in [[#tarfile.TarInfo|<code>TarInfo</code>]] objects of type <code>LNKTYPE</code> and <code>SYMTYPE</code>.
+
: 目标文件名的名称,仅存在于 <code>LNKTYPE</code> <code>SYMTYPE</code> 类型的 [[#tarfile.TarInfo|TarInfo]] 对象中。
  
; <code>TarInfo.</code><code>uid</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">uid</span></span>
: User ID of the user who originally stored this member.
+
: 最初存储此成员的用户的用户 ID。
  
; <code>TarInfo.</code><code>gid</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">gid</span></span>
: Group ID of the user who originally stored this member.
+
: 最初存储此成员的用户的组 ID。
  
; <code>TarInfo.</code><code>uname</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">uname</span></span>
: User name.
+
: 用户名。
  
; <code>TarInfo.</code><code>gname</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">gname</span></span>
: Group name.
+
: 团队名字。
  
; <code>TarInfo.</code><code>pax_headers</code>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">pax_headers</span></span>
: A dictionary containing key-value pairs of an associated pax extended header.
+
: 包含关联 pax 扩展标头的键值对的字典。
  
A [[#tarfile.TarInfo|<code>TarInfo</code>]] object also provides some convenient query methods:
+
[[#tarfile.TarInfo|TarInfo]] 对象还提供了一些方便的查询方法:
  
; <code>TarInfo.</code><code>isfile</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isfile</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if the <code>Tarinfo</code> object is a regular file.
+
: 如果 <code>Tarinfo</code> 对象是常规文件,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>isreg</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isreg</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Same as [[#tarfile.TarInfo.isfile|<code>isfile()</code>]].
+
: [[#tarfile.TarInfo.isfile|isfile()]] 相同。
  
; <code>TarInfo.</code><code>isdir</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isdir</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a directory.
+
: 如果是目录,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>issym</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">issym</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a symbolic link.
+
: 如果是符号链接,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>islnk</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">islnk</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a hard link.
+
: 如果是硬链接,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>ischr</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">ischr</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a character device.
+
: 如果是字符设备,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>isblk</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isblk</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a block device.
+
: 如果是块设备,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>isfifo</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isfifo</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is a FIFO.
+
: 如果是 FIFO,则返回 [[../constants#True|True]]
  
; <code>TarInfo.</code><code>isdev</code><span class="sig-paren">(</span><span class="sig-paren">)</span>
+
; <span class="sig-prename descclassname"><span class="pre">TarInfo.</span></span><span class="sig-name descname"><span class="pre">isdev</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span>
: Return [[../constants#True|<code>True</code>]] if it is one of character device, block device or FIFO.
+
: 如果是字符设备、块设备或 FIFO 之一,则返回 [[../constants#True|True]]
  
  
第599行: 第472行:
  
 
<span id="tarfile-commandline"></span>
 
<span id="tarfile-commandline"></span>
== Command-Line Interface ==
+
== 命令行界面 ==
  
 
<div class="versionadded">
 
<div class="versionadded">
  
<span class="versionmodified added">3.4 新版功能.</span>
+
<span class="versionmodified added">3.4 版中的新功能。</span>
  
  
 
</div>
 
</div>
The [[#module-tarfile|<code>tarfile</code>]] module provides a simple command-line interface to interact
+
[[#module-tarfile|tarfile]] 模块提供了一个简单的命令行界面来与 tar 档案交互。
with tar archives.
 
  
If you want to create a new tar archive, specify its name after the [[#cmdoption-tarfile-c|<code>-c</code>]]
+
如果要创建新的 tar 存档,请在 [[#cmdoption-tarfile-c|-c]] 选项后指定其名称,然后列出应包含的文件名:
option and then list the filename(s) that should be included:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第617行: 第488行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python -m tarfile -c monty.tar  spam.txt eggs.txt</pre>
+
<pre class="session">$ python -m tarfile -c monty.tar  spam.txt eggs.txt</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
Passing a directory is also acceptable:
+
传递目录也是可以接受的:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第628行: 第499行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python -m tarfile -c monty.tar life-of-brian_1979/</pre>
+
<pre class="session">$ python -m tarfile -c monty.tar life-of-brian_1979/</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
If you want to extract a tar archive into the current directory, use
+
如果要将 tar 存档解压缩到当前目录,请使用 [[#cmdoption-tarfile-e|-e]] 选项:
the [[#cmdoption-tarfile-e|<code>-e</code>]] option:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第640行: 第510行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python -m tarfile -e monty.tar</pre>
+
<pre class="session">$ python -m tarfile -e monty.tar</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
You can also extract a tar archive into a different directory by passing the
+
您还可以通过传递目录的名称将 tar 存档解压缩到不同的目录中:
directory's name:
 
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第652行: 第521行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python -m tarfile -e monty.tar  other-dir/</pre>
+
<pre class="session">$ python -m tarfile -e monty.tar  other-dir/</pre>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
For a list of the files in a tar archive, use the [[#cmdoption-tarfile-l|<code>-l</code>]] option:
+
要获取 tar 存档中的文件列表,请使用 [[#cmdoption-tarfile-l|-l]] 选项:
  
 
<div class="highlight-shell-session notranslate">
 
<div class="highlight-shell-session notranslate">
第663行: 第532行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>$ python -m tarfile -l monty.tar</pre>
+
<pre class="session">$ python -m tarfile -l monty.tar</pre>
  
 
</div>
 
</div>
第670行: 第539行:
 
<div id="command-line-options" class="section">
 
<div id="command-line-options" class="section">
  
=== Command-line options ===
+
=== 命令行选项 ===
  
; <code>-l</code><code> &lt;tarfile&gt;</code><br />
+
; <span class="sig-name descname"><span class="pre">-l</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span></span><br />
<code>--list</code><code> &lt;tarfile&gt;</code>
+
<span class="sig-name descname"><span class="pre">--list</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span></span>
: List files in a tarfile.
+
: 列出 tarfile 中的文件。
  
; <code>-c</code><code> &lt;tarfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;</code><br />
+
; <span class="sig-name descname"><span class="pre">-c</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span> <span class="pre">&lt;source1&gt;</span> <span class="pre">...</span> <span class="pre">&lt;sourceN&gt;</span></span><br />
<code>--create</code><code> &lt;tarfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;</code>
+
<span class="sig-name descname"><span class="pre">--create</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span> <span class="pre">&lt;source1&gt;</span> <span class="pre">...</span> <span class="pre">&lt;sourceN&gt;</span></span>
: Create tarfile from source files.
+
: 从源文件创建 tarfile。
  
; <code>-e</code><code> &lt;tarfile&gt; [&lt;output_dir&gt;]</code><br />
+
; <span class="sig-name descname"><span class="pre">-e</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span> <span class="pre">[&lt;output_dir&gt;]</span></span><br />
<code>--extract</code><code> &lt;tarfile&gt; [&lt;output_dir&gt;]</code>
+
<span class="sig-name descname"><span class="pre">--extract</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span> <span class="pre">[&lt;output_dir&gt;]</span></span>
: Extract tarfile into the current directory if ''output_dir'' is not specified.
+
: 如果未指定 ''output_dir'',则将 tarfile 提取到当前目录中。
  
; <code>-t</code><code> &lt;tarfile&gt;</code><br />
+
; <span class="sig-name descname"><span class="pre">-t</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span></span><br />
<code>--test</code><code> &lt;tarfile&gt;</code>
+
<span class="sig-name descname"><span class="pre">--test</span></span><span class="sig-prename descclassname"> <span class="pre">&lt;tarfile&gt;</span></span>
: Test whether the tarfile is valid or not.
+
: 测试 tarfile 是否有效。
  
; <span id="cmdoption-tarfile-verbose"></span><code>-v</code><code></code><code>, </code><code>--verbose</code><code></code>
+
; <span id="cmdoption-tarfile-verbose"></span><span class="sig-name descname"><span class="pre">-v</span></span><span class="sig-prename descclassname"></span><span class="sig-prename descclassname"><span class="pre">,</span> </span><span class="sig-name descname"><span class="pre">--verbose</span></span><span class="sig-prename descclassname"></span>
: Verbose output.
+
: 详细输出。
  
  
第698行: 第567行:
  
 
<span id="tar-examples"></span>
 
<span id="tar-examples"></span>
== Examples ==
+
== 例子 ==
  
How to extract an entire tar archive to the current working directory:
+
如何将整个 tar 存档解压缩到当前工作目录:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第706行: 第575行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import tarfile
+
<syntaxhighlight lang="python3">import tarfile
tar = tarfile.open(&quot;sample.tar.gz&quot;)
+
tar = tarfile.open("sample.tar.gz")
 
tar.extractall()
 
tar.extractall()
tar.close()</pre>
+
tar.close()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
How to extract a subset of a tar archive with [[#tarfile.TarFile.extractall|<code>TarFile.extractall()</code>]] using
+
如何使用生成器函数而不是列表提取带有 [[#tarfile.TarFile.extractall|TarFile.extractall()]] 的 tar 存档的子集:
a generator function instead of a list:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第721行: 第589行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import os
+
<syntaxhighlight lang="python3">import os
 
import tarfile
 
import tarfile
  
 
def py_files(members):
 
def py_files(members):
 
     for tarinfo in members:
 
     for tarinfo in members:
         if os.path.splitext(tarinfo.name)[1] == &quot;.py&quot;:
+
         if os.path.splitext(tarinfo.name)[1] == ".py":
 
             yield tarinfo
 
             yield tarinfo
  
tar = tarfile.open(&quot;sample.tar.gz&quot;)
+
tar = tarfile.open("sample.tar.gz")
 
tar.extractall(members=py_files(tar))
 
tar.extractall(members=py_files(tar))
tar.close()</pre>
+
tar.close()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
How to create an uncompressed tar archive from a list of filenames:
+
如何从文件名列表创建未压缩的 tar 存档:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第742行: 第610行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import tarfile
+
<syntaxhighlight lang="python3">import tarfile
tar = tarfile.open(&quot;sample.tar&quot;, &quot;w&quot;)
+
tar = tarfile.open("sample.tar", "w")
for name in [&quot;foo&quot;, &quot;bar&quot;, &quot;quux&quot;]:
+
for name in ["foo", "bar", "quux"]:
 
     tar.add(name)
 
     tar.add(name)
tar.close()</pre>
+
tar.close()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
The same example using the [[../../reference/compound_stmts#with|<code>with</code>]] statement:
+
使用 [[../../reference/compound_stmts#with|with]] 语句的相同示例:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第757行: 第625行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import tarfile
+
<syntaxhighlight lang="python3">import tarfile
with tarfile.open(&quot;sample.tar&quot;, &quot;w&quot;) as tar:
+
with tarfile.open("sample.tar", "w") as tar:
     for name in [&quot;foo&quot;, &quot;bar&quot;, &quot;quux&quot;]:
+
     for name in ["foo", "bar", "quux"]:
         tar.add(name)</pre>
+
         tar.add(name)</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
How to read a gzip compressed tar archive and display some member information:
+
如何读取 gzip 压缩的 tar 存档并显示一些成员信息:
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第771行: 第639行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import tarfile
+
<syntaxhighlight lang="python3">import tarfile
tar = tarfile.open(&quot;sample.tar.gz&quot;, &quot;r:gz&quot;)
+
tar = tarfile.open("sample.tar.gz", "r:gz")
 
for tarinfo in tar:
 
for tarinfo in tar:
     print(tarinfo.name, &quot;is&quot;, tarinfo.size, &quot;bytes in size and is &quot;, end=&quot;&quot;)
+
     print(tarinfo.name, "is", tarinfo.size, "bytes in size and is ", end="")
 
     if tarinfo.isreg():
 
     if tarinfo.isreg():
         print(&quot;a regular file.&quot;)
+
         print("a regular file.")
 
     elif tarinfo.isdir():
 
     elif tarinfo.isdir():
         print(&quot;a directory.&quot;)
+
         print("a directory.")
 
     else:
 
     else:
         print(&quot;something else.&quot;)
+
         print("something else.")
tar.close()</pre>
+
tar.close()</syntaxhighlight>
  
 
</div>
 
</div>
  
 
</div>
 
</div>
How to create an archive and reset the user information using the ''filter''
+
如何使用 [[#tarfile.TarFile.add|TarFile.add()]] 中的 ''filter'' 参数创建存档和重置用户信息:
parameter in [[#tarfile.TarFile.add|<code>TarFile.add()</code>]]:
 
  
 
<div class="highlight-python3 notranslate">
 
<div class="highlight-python3 notranslate">
第793行: 第660行:
 
<div class="highlight">
 
<div class="highlight">
  
<pre>import tarfile
+
<syntaxhighlight lang="python3">import tarfile
 
def reset(tarinfo):
 
def reset(tarinfo):
 
     tarinfo.uid = tarinfo.gid = 0
 
     tarinfo.uid = tarinfo.gid = 0
     tarinfo.uname = tarinfo.gname = &quot;root&quot;
+
     tarinfo.uname = tarinfo.gname = "root"
 
     return tarinfo
 
     return tarinfo
tar = tarfile.open(&quot;sample.tar.gz&quot;, &quot;w:gz&quot;)
+
tar = tarfile.open("sample.tar.gz", "w:gz")
tar.add(&quot;foo&quot;, filter=reset)
+
tar.add("foo", filter=reset)
tar.close()</pre>
+
tar.close()</syntaxhighlight>
  
 
</div>
 
</div>
第810行: 第677行:
  
 
<span id="tar-formats"></span>
 
<span id="tar-formats"></span>
== Supported tar formats ==
+
== 支持的 tar 格式 ==
  
There are three tar formats that can be created with the [[#module-tarfile|<code>tarfile</code>]] module:
+
可以使用 [[#module-tarfile|tarfile]] 模块创建三种 tar 格式:
  
 
<ul>
 
<ul>
<li><p>The POSIX.1-1988 ustar format ([[#tarfile.USTAR_FORMAT|<code>USTAR_FORMAT</code>]]). It supports filenames
+
<li><p>POSIX.1-1988 ustar 格式 ([[#tarfile.USTAR_FORMAT|USTAR_FORMAT]])。 它支持最多 256 个字符的文件名和最多 100 个字符的链接名。 最大文件大小为 8 GiB。 这是一种古老而有限但得到广泛支持的格式。</p></li>
up to a length of at best 256 characters and linknames up to 100 characters.
+
<li><p>GNU tar 格式 ([[#tarfile.GNU_FORMAT|GNU_FORMAT]])。 它支持长文件名和链接名、大于 8 GiB 的文件和稀疏文件。 它是 GNU/Linux 系统上的事实标准。 [[#module-tarfile|tarfile]] 完全支持长名称的 GNU tar 扩展,稀疏文件支持是只读的。</p></li>
The maximum file size is 8 GiB. This is an old and limited but widely
+
<li><p>POSIX.1-2001 pax 格式 ([[#tarfile.PAX_FORMAT|PAX_FORMAT]])。 它是最灵活的格式,几乎没有限制。 它支持长文件名和链接名、大文件并以可移植的方式存储路径名。 现代 tar 实现,包括 GNU tar、bsdtar/libarchive 和 star,完全支持扩展的 ''pax'' 功能; 一些旧的或未维护的库可能不会,但应该将 ''pax'' 档案视为普遍支持的 ''ustar'' 格式。 它是新档案的当前默认格式。</p>
supported format.</p></li>
+
<p>它扩展了现有的 ''ustar'' 格式,为无法以其他方式存储的信息提供额外的标头。 pax 头有两种风格:扩展头仅影响后续文件头,全局头对完整存档有效并影响所有后续文件。 出于可移植性的原因,pax 标头中的所有数据都以 ''UTF-8'' 编码。</p></li></ul>
<li><p>The GNU tar format ([[#tarfile.GNU_FORMAT|<code>GNU_FORMAT</code>]]). It supports long filenames and
 
linknames, files bigger than 8 GiB and sparse files. It is the de facto
 
standard on GNU/Linux systems. [[#module-tarfile|<code>tarfile</code>]] fully supports the GNU tar
 
extensions for long names, sparse file support is read-only.</p></li>
 
<li><p>The POSIX.1-2001 pax format ([[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]]). 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 ''pax''
 
features; some old or unmaintained libraries may not, but should treat
 
''pax'' archives as if they were in the universally-supported ''ustar'' format.
 
It is the current default format for new archives.</p>
 
<p>It extends the existing ''ustar'' 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 ''UTF-8'' for portability reasons.</p></li></ul>
 
  
There are some more variants of the tar format which can be read, but not
+
还有一些 tar 格式的变体可以读取,但不能创建:
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.
+
* 古老的 V7 格式。 这是 Unix 第七版的第一个 tar 格式,仅存储常规文件和目录。 名称不得超过 100 个字符,没有用户/组名称信息。 如果字段包含非 ASCII 字符,某些存档会错误计算标头校验和。
* The SunOS tar extended format. This format is a variant of the POSIX.1-2001 pax format, but is not compatible.
+
* SunOS tar 扩展格式。 此格式是 POSIX.1-2001 pax 格式的变体,但不兼容。
  
  
第847行: 第697行:
  
 
<span id="tar-unicode"></span>
 
<span id="tar-unicode"></span>
== Unicode issues ==
+
== Unicode 问题 ==
 +
 
 +
tar 格式最初的构想是在磁带驱动器上进行备份,主要侧重于保留文件系统信息。 如今,tar 档案通常用于文件分发和通过网络交换档案。 原始格式(它是所有其他格式的基础)的一个问题是没有支持不同字符编码的概念。 例如,在 ''UTF-8'' 系统上创建的普通 tar 存档如果包含非 ''ASCII'' 字符,则无法在 ''Latin-1'' 系统上正确读取。 文本元数据(如文件名、链接名、用户/组名)将出现损坏。 不幸的是,没有办法自动检测档案的编码。 pax 格式旨在解决这个问题。 它使用通用字符编码 ''UTF-8'' 存储非 ASCII 元数据。
  
The tar format was originally conceived to make backups on tape drives with the
+
[[#module-tarfile|tarfile]] 中字符转换的细节由 [[#tarfile.TarFile|TarFile]] 类的 ''encoding'' ''errors'' 关键字参数控制。
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 [[#module-tarfile|<code>tarfile</code>]] are controlled by the
+
''encoding'' 定义用于存档中元数据的字符编码。 默认值为 [[../sys#sys|sys.getfilesystemencoding()]] 或 <code>'ascii'</code> 作为后备。 根据档案是读取还是写入,元数据必须被解码或编码。 如果 ''encoding'' 设置不正确,此转换可能会失败。
''encoding'' and ''errors'' keyword arguments of the [[#tarfile.TarFile|<code>TarFile</code>]] class.
 
  
''encoding'' defines the character encoding to use for the metadata in the
+
''errors'' 参数定义了如何处理无法转换的字符。 可能的值列在 [[../codecs#error-handlers|错误处理程序]] 部分。 默认方案是 <code>'surrogateescape'</code>,Python 也使用它进行文件系统调用,请参阅 [[../os#os-filenames|文件名、命令行参数和环境变量]] 。
archive. The default value is [[../sys#sys|<code>sys.getfilesystemencoding()</code>]] 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 ''encoding'' is not set
 
appropriately, this conversion may fail.
 
  
The ''errors'' argument defines how characters are treated that cannot be
+
对于 [[#tarfile.PAX_FORMAT|PAX_FORMAT]] 档案(默认),通常不需要 ''encoding'',因为所有元数据都使用 ''UTF-8'' 存储。 ''encoding'' 仅用于在解码二进制 pax 标头或存储具有代理字符的字符串时的极少数情况。
converted. Possible values are listed in section [[../codecs#error-handlers|<span class="std std-ref">Error Handlers</span>]].
 
The default scheme is <code>'surrogateescape'</code> which Python also uses for its
 
file system calls, see [[../os#os-filenames|<span class="std std-ref">File Names, Command Line Arguments, and Environment Variables</span>]].
 
  
For [[#tarfile.PAX_FORMAT|<code>PAX_FORMAT</code>]] archives (the default), ''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.
 
  
 +
</div>
  
 
</div>
 
</div>
 +
<div class="clearer">
 +
 +
  
 
</div>
 
</div>
  
[[Category:Python 3.9 中文文档]]
+
[[Category:Python 3.9 文档]]

2021年10月31日 (日) 04:53的最新版本

tarfile — 读写 tar 归档文件

源代码: :source:`Lib/tarfile.py`



tarfile 模块可以读取和写入 tar 档案,包括使用 gzip、bz2 和 lzma 压缩的档案。 使用 zipfile 模块读取或写入 .zip 文件,或 shutil 中的更高级别函数。

一些事实和数据:

  • 如果相应的模块可用,则读取和写入 gzipbz2lzma 压缩档案。
  • 对 POSIX.1-1988 (ustar) 格式的读/写支持。
  • 对 GNU tar 格式的读/写支持,包括 longnamelonglink 扩展,只读支持 sparse 扩展的所有变体,包括稀疏文件的恢复。
  • 对 POSIX.1-2001 (pax) 格式的读/写支持。
  • 处理目录、常规文件、硬链接、符号链接、fifos、字符设备和块设备,并能够获取和恢复文件信息,如时间戳、访问权限和所有者。

3.3 版更改: 添加了对 lzma 压缩的支持。


tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)

为路径名 name 返回一个 TarFile 对象。 有关 TarFile 对象和允许的关键字参数的详细信息,请参阅 TarFile 对象

mode 必须是 'filemode[:compression]' 形式的字符串,默认为 'r'。 以下是模式组合的完整列表:

模式

行动

'r' or 'r:*'

使用透明压缩打开阅读(推荐)。

'r:'

开放阅读,无需压缩。

'r:gz'

使用 gzip 压缩打开以供阅读。

'r:bz2'

使用 bzip2 压缩打开以供阅读。

'r:xz'

使用 lzma 压缩打开阅读。

'x''x:'

创建一个不压缩的 tarfile。 如果已存在,则引发 FileExistsError 异常。

'x:gz'

使用 gzip 压缩创建一个 tarfile。 如果已存在,则引发 FileExistsError 异常。

'x:bz2'

使用 bzip2 压缩创建一个 tarfile。 如果已存在,则引发 FileExistsError 异常。

'x:xz'

使用 lzma 压缩创建一个 tarfile。 如果已存在,则引发 FileExistsError 异常。

'a' or 'a:'

打开以追加,无压缩。 如果文件不存在,则创建该文件。

'w' or 'w:'

打开无压缩写入。

'w:gz'

打开 gzip 压缩写入。

'w:bz2'

为 bzip2 压缩写入打开。

'w:xz'

打开 lzma 压缩写入。

请注意,'a:gz''a:bz2''a:xz' 是不可能的。 如果 mode 不适合打开某个(压缩)文件进行读取,则会引发 ReadError。 使用 mode 'r' 来避免这种情况。 如果不支持压缩方法,则会引发 CompressionError

如果指定了 fileobj,它被用作 name 以二进制模式打开的 文件对象 的替代。 它应该在位置 0。

对于模式 'w:gz''r:gz''w:bz2''r:bz2''x:gz''x:bz2'tarfile.open () 接受关键字参数 compresslevel(默认 9)来指定文件的压缩级别。

对于模式 'w:xz''x:xz'tarfile.open() 接受关键字参数 preset 来指定文件的压缩级别。

出于特殊目的,模式还有第二种格式:'filemode|[compression]'tarfile.open() 将返回一个 TarFile 对象,该对象将其数据作为块流处理。 不会对文件进行随机搜索。 如果给定,fileobj 可以是任何具有 read()write() 方法的对象(取决于 mode)。 bufsize 指定块大小,默认为 20 * 512 字节。 将此变体与例如结合使用 sys.stdin、套接字 文件对象 或磁带设备。 然而,这样的 TarFile 对象受到限制,因为它不允许随机访问,请参阅 示例 。 当前可能的模式:

模式

行动

*'

打开 tar 块的 以使用透明压缩进行读取。

'

打开未压缩的 tar 块的 以进行读取。

gz'

打开 gzip 压缩的 stream 进行阅读。

bz2'

打开一个 bzip2 压缩的 stream 进行读取。

xz'

打开一个 lzma 压缩的 stream 进行读取。

'

打开未压缩的 进行写入。

gz'

打开一个 gzip 压缩的 stream 进行写入。

bz2'

打开一个 bzip2 压缩的 stream 进行写入。

xz'

打开一个 lzma 压缩的 stream 进行写入。

3.5版本变更:增加了'x'(独创)模式。

3.6 版更改: name 参数接受 类路径对象

class tarfile.TarFile
用于读取和写入 tar 档案的类。 不要直接使用这个类:使用 tarfile.open() 代替。 参见 TarFile 对象
tarfile.is_tarfile(name)

如果 name 是 tar 存档文件,则返回 Truetarfile 模块可以读取该文件。 name 可以是 str、文件或类似文件的对象。

3.9 版更改: 支持文件和类文件对象。

tarfile 模块定义了以下异常:

exception tarfile.TarError
所有 tarfile 异常的基类。
exception tarfile.ReadError
在打开 tar 存档时引发,tarfile 模块无法处理或以某种方式无效。
exception tarfile.CompressionError
当不支持压缩方法或无法正确解码数据时引发。
exception tarfile.StreamError
由于流类 TarFile 对象的典型限制而引发。
exception tarfile.ExtractError
使用 TarFile.extract() 时,针对 非致命 错误引发,但仅在 TarFile.errorlevel== 2 时引发。
exception tarfile.HeaderError
如果它获得的缓冲区无效,则由 TarInfo.frombuf() 引发。

以下常量在模块级别可用:

tarfile.ENCODING
默认字符编码:Windows 上的 'utf-8',否则为 sys.getfilesystemencoding() 返回的值。

以下每个常量定义了 tarfile 模块能够创建的 tar 存档格式。 有关详细信息,请参阅 支持的 tar 格式 部分。

tarfile.USTAR_FORMAT
POSIX.1-1988 (ustar) 格式。
tarfile.GNU_FORMAT
GNU tar 格式。
tarfile.PAX_FORMAT
POSIX.1-2001 (pax) 格式。
tarfile.DEFAULT_FORMAT

创建档案的默认格式。 目前是 PAX_FORMAT

3.8 版更改: 新存档的默认格式从 GNU_FORMAT 更改为 PAX_FORMAT

也可以看看

模块 zipfile
zipfile 标准模块的文档。
归档操作
标准 shutil 模块提供的更高级别归档工具的文档。
GNU tar 手册,基本 Tar 格式
tar 存档文件的文档,包括 GNU tar 扩展。


TarFile 对象

TarFile 对象提供了一个 tar 存档的接口。 tar 档案是一个块序列。 归档成员(存储的文件)由头块和数据块组成。 可以将文件多次存储在 tar 存档中。 每个存档成员都由一个 TarInfo 对象表示,有关详细信息,请参阅 TarInfo 对象

TarFile 对象可以用作 with 语句中的上下文管理器。 当块完成时它会自动关闭。 请注意,如果出现异常情况,为写入而打开的存档将不会被最终确定; 只有内部使用的文件对象将被关闭。 有关用例,请参阅 示例 部分。

3.2 新功能: 增加了对上下文管理协议的支持。


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=0)

以下所有参数都是可选的,也可以作为实例属性访问。

name 是存档的路径名。 name 可能是一个 类似路径的对象 。 如果给出 fileobj,则可以省略。 在这种情况下,如果存在文件对象的 name 属性,则使用该属性。

mode'r' 从现有档案中读取,'a' 将数据附加到现有文件,'w' 创建一个覆盖现有文件的新文件一个,或 'x' 仅在新文件不存在时创建新文件。

如果给出 fileobj,则用于读取或写入数据。 如果可以确定,则 modefileobj 的模式覆盖。 fileobj 将从位置 0 开始使用。

笔记

fileobj 不关闭,当 TarFile 关闭时。

format 控制写入的存档格式。 它必须是在模块级别定义的常量 USTAR_FORMATGNU_FORMATPAX_FORMAT 之一。 读取时,即使单个存档中存在不同的格式,也会自动检测格式。

tarinfo 参数可用于用不同的类替换默认的 TarInfo 类。

如果 dereferenceFalse,则将符号链接和硬链接添加到存档。 如果是True,则将目标文件的内容添加到存档中。 这对不支持符号链接的系统没有影响。

如果 ignore_zerosFalse,则将空块视为存档的结尾。 如果是 True,则跳过空(和无效)块并尝试获取尽可能多的成员。 这仅对读取连接或损坏的档案有用。

debug 可以设置为从 0(无调试消息)到 3(所有调试消息)。 消息写入 sys.stderr

如果 errorlevel0,则使用 TarFile.extract() 时会忽略所有错误。 然而,当启用调试时,它们在调试输出中显示为错误消息。 如果 1,则所有 fatal 错误都作为 OSError 异常引发。 如果 2,所有 非致命 错误也会作为 TarError 异常引发。

encodingerrors 参数定义了用于读取或写入存档的字符编码以及将如何处理转换错误。 默认设置适用于大多数用户。 有关详细信息,请参阅 Unicode 问题 部分。

pax_headers 参数是一个可选的字符串字典,如果 formatPAX_FORMAT,它将作为 pax 全局标头添加。

3.2 版更改: 使用 'surrogateescape' 作为 errors 参数的默认值。

3.5版本变更:增加了'x'(独创)模式。

3.6 版更改: name 参数接受 类路径对象

classmethod TarFile.open(...)
替代构造函数。 tarfile.open() 函数实际上是这个类方法的快捷方式。
TarFile.getmember(name)

为成员 name 返回一个 TarInfo 对象。 如果在存档中找不到 name,则会引发 KeyError

笔记

如果某个成员在存档中出现多次,则假定其最后一次出现是最新版本。

TarFile.getmembers()
将存档成员作为 TarInfo 对象列表返回。 该列表与存档中的成员具有相同的顺序。
TarFile.getnames()
将成员作为其姓名列表返回。 它与 getmembers() 返回的列表具有相同的顺序。
TarFile.list(verbose=True, *, members=None)

将目录打印到 sys.stdout。 如果 verboseFalse,则仅打印成员的名称。 如果是 True,则产生类似于 ls -l 的输出。 如果给出了可选的 members,它必须是由 getmembers() 返回的列表的子集。

3.5 版更改: 增加了 members 参数。

TarFile.next()
当打开 TarFile 进行读取时,将存档的下一个成员作为 TarInfo 对象返回。 如果没有更多可用,则返回 None
TarFile.extractall(path='.', members=None, *, numeric_owner=False)

将存档中的所有成员提取到当前工作目录或目录 path。 如果给出了可选的 members,它必须是由 getmembers() 返回的列表的子集。 在提取所有成员后设置目录信息,如所有者、修改时间和权限。 这样做是为了解决两个问题: 每次在其中创建文件时都会重置目录的修改时间。 而且,如果目录的权限不允许写入,则将文件提取到该目录将失败。

如果 numeric_ownerTrue,则 tarfile 中的 uid 和 gid 编号用于设置提取文件的所有者/组。 否则,将使用 tarfile 中的命名值。

警告

未经事先检查,切勿从不受信任的来源提取档案。 文件可能是在 path 之外创建的,例如 具有以 "/" 开头的绝对文件名或以两个点 ".." 开头的文件名的成员。

3.5 版更改: 添加 numeric_owner 参数。

在 3.6 版更改:path 参数接受一个 path-like object

TarFile.extract(member, path=, set_attrs=True, *, numeric_owner=False)

使用其全名从存档中提取成员到当前工作目录。 尽可能准确地提取其文件信息。 member 可以是文件名或 TarInfo 对象。 您可以使用 path 指定不同的目录。 path 可能是一个 path-like object。 除非 set_attrs 为 false,否则设置文件属性(所有者、mtime、模式)。

如果 numeric_ownerTrue,则 tarfile 中的 uid 和 gid 编号用于设置提取文件的所有者/组。 否则,将使用 tarfile 中的命名值。

笔记

extract() 方法不处理几个提取问题。 在大多数情况下,您应该考虑使用 extractall() 方法。

警告

请参阅 extractall() 的警告。

3.2 版更改: 添加 set_attrs 参数。

3.5 版更改: 添加 numeric_owner 参数。

在 3.6 版更改:path 参数接受一个 path-like object

TarFile.extractfile(member)

从存档中提取成员作为文件对象。 member 可以是文件名或 TarInfo 对象。 如果 member 是常规文件或链接,则返回 io.BufferedReader 对象。 对于所有其他现有成员,返回 None。 如果 member 未出现在存档中,则会引发 KeyError

3.3 版更改: 返回 io.BufferedReader 对象。

TarFile.add(name, arcname=None, recursive=True, *, filter=None)

将文件 name 添加到存档中。 name 可以是任何类型的文件(目录、fifo、符号链接等)。 如果给定,arcname 指定存档中文件的替代名称。 默认情况下以递归方式添加目录。 这可以通过将 recursive 设置为 False 来避免。 递归按排序顺序添加条目。 如果给出 filter,它应该是一个函数,它接受一个 TarInfo 对象参数并返回改变后的 TarInfo 对象。 如果它返回 None,则 TarInfo 对象将从存档中排除。 有关示例,请参阅 示例

3.2 版更改: 添加 过滤器 参数。

3.7 版更改: 递归按排序顺序添加条目。

TarFile.addfile(tarinfo, fileobj=None)
TarInfo 对象 tarinfo 添加到存档中。 如果给出 fileobj,它应该是一个 二进制文件 ,从中读取 tarinfo.size 字节并添加到存档中。 您可以直接创建 TarInfo 对象,也可以使用 gettarinfo()
TarFile.gettarinfo(name=None, arcname=None, fileobj=None)

根据现有文件上的 os.stat() 或等效结果创建 TarInfo 对象。 该文件要么由 name 命名,要么指定为 file object fileobj 和文件描述符。 name 可能是一个 类似路径的对象 。 如果给定,arcname 指定存档中文件的替代名称,否则,名称取自 fileobjname 属性,或 ]name 参数。 名称应为文本字符串。

在使用 addfile() 添加之前,您可以修改 TarInfo 的一些属性。 如果文件对象不是位于文件开头的普通文件对象,可能需要修改size等属性。 对于诸如 GzipFile 之类的对象就是这种情况。 name 也可以修改,在这种情况下 arcname 可能是一个虚拟字符串。

3.6 版更改: name 参数接受 类路径对象

TarFile.close()
关闭 TarFile。 在写入模式下,两个完成零块被附加到存档中。
TarFile.pax_headers
包含 pax 全局标头的键值对的字典。


TarInfo 对象

TarInfo 对象代表 TarFile 中的一个成员。 除了存储文件的所有必需属性(如文件类型、大小、时间、权限、所有者等)外,它还提供了一些有用的方法来确定其类型。 它确实 包含文件本身的数据。

TarInfo 对象由 TarFile 的方法 getmember()getmembers()gettarinfo() 返回。

class tarfile.TarInfo(name=)
创建一个 TarInfo 对象。
classmethod TarInfo.frombuf(buf, encoding, errors)

从字符串缓冲区 buf 创建并返回一个 TarInfo 对象。

如果缓冲区无效,则引发 HeaderError

classmethod TarInfo.fromtarfile(tarfile)
TarFile 对象 tarfile 读取下一个成员并将其作为 TarInfo 对象返回。
TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')

TarInfo 对象创建字符串缓冲区。 有关参数的信息,请参阅 TarFile 类的构造函数。

3.2 版更改: 使用 'surrogateescape' 作为 errors 参数的默认值。

TarInfo 对象具有以下公共数据属性:

TarInfo.name
存档成员的名称。
TarInfo.size
以字节为单位的大小。
TarInfo.mtime
上次修改时间。
TarInfo.mode
权限位。
TarInfo.type
文件类型。 type 通常是以下常量之一:REGTYPEAREGTYPELNKTYPESYMTYPEDIRTYPE、[ X104X]、CONTTYPECHRTYPEBLKTYPEGNUTYPE_SPARSE。 要更方便地确定 TarInfo 对象的类型,请使用下面的 is*() 方法。
TarInfo.linkname
目标文件名的名称,仅存在于 LNKTYPESYMTYPE 类型的 TarInfo 对象中。
TarInfo.uid
最初存储此成员的用户的用户 ID。
TarInfo.gid
最初存储此成员的用户的组 ID。
TarInfo.uname
用户名。
TarInfo.gname
团队名字。
TarInfo.pax_headers
包含关联 pax 扩展标头的键值对的字典。

TarInfo 对象还提供了一些方便的查询方法:

TarInfo.isfile()
如果 Tarinfo 对象是常规文件,则返回 True
TarInfo.isreg()
isfile() 相同。
TarInfo.isdir()
如果是目录,则返回 True
TarInfo.issym()
如果是符号链接,则返回 True
TarInfo.islnk()
如果是硬链接,则返回 True
TarInfo.ischr()
如果是字符设备,则返回 True
TarInfo.isblk()
如果是块设备,则返回 True
TarInfo.isfifo()
如果是 FIFO,则返回 True
TarInfo.isdev()
如果是字符设备、块设备或 FIFO 之一,则返回 True


命令行界面

3.4 版中的新功能。


tarfile 模块提供了一个简单的命令行界面来与 tar 档案交互。

如果要创建新的 tar 存档,请在 -c 选项后指定其名称,然后列出应包含的文件名:

$ python -m tarfile -c monty.tar  spam.txt eggs.txt

传递目录也是可以接受的:

$ python -m tarfile -c monty.tar life-of-brian_1979/

如果要将 tar 存档解压缩到当前目录,请使用 -e 选项:

$ python -m tarfile -e monty.tar

您还可以通过传递目录的名称将 tar 存档解压缩到不同的目录中:

$ python -m tarfile -e monty.tar  other-dir/

要获取 tar 存档中的文件列表,请使用 -l 选项:

$ python -m tarfile -l monty.tar

命令行选项

-l <tarfile>

--list <tarfile>

列出 tarfile 中的文件。
-c <tarfile> <source1> ... <sourceN>

--create <tarfile> <source1> ... <sourceN>

从源文件创建 tarfile。
-e <tarfile> [<output_dir>]

--extract <tarfile> [<output_dir>]

如果未指定 output_dir,则将 tarfile 提取到当前目录中。
-t <tarfile>

--test <tarfile>

测试 tarfile 是否有效。
-v, --verbose
详细输出。


例子

如何将整个 tar 存档解压缩到当前工作目录:

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

如何使用生成器函数而不是列表提取带有 TarFile.extractall() 的 tar 存档的子集:

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()

如何从文件名列表创建未压缩的 tar 存档:

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

使用 with 语句的相同示例:

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

如何读取 gzip 压缩的 tar 存档并显示一些成员信息:

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()

如何使用 TarFile.add() 中的 filter 参数创建存档和重置用户信息:

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()

支持的 tar 格式

可以使用 tarfile 模块创建三种 tar 格式:

  • POSIX.1-1988 ustar 格式 (USTAR_FORMAT)。 它支持最多 256 个字符的文件名和最多 100 个字符的链接名。 最大文件大小为 8 GiB。 这是一种古老而有限但得到广泛支持的格式。

  • GNU tar 格式 (GNU_FORMAT)。 它支持长文件名和链接名、大于 8 GiB 的文件和稀疏文件。 它是 GNU/Linux 系统上的事实标准。 tarfile 完全支持长名称的 GNU tar 扩展,稀疏文件支持是只读的。

  • POSIX.1-2001 pax 格式 (PAX_FORMAT)。 它是最灵活的格式,几乎没有限制。 它支持长文件名和链接名、大文件并以可移植的方式存储路径名。 现代 tar 实现,包括 GNU tar、bsdtar/libarchive 和 star,完全支持扩展的 pax 功能; 一些旧的或未维护的库可能不会,但应该将 pax 档案视为普遍支持的 ustar 格式。 它是新档案的当前默认格式。

    它扩展了现有的 ustar 格式,为无法以其他方式存储的信息提供额外的标头。 pax 头有两种风格:扩展头仅影响后续文件头,全局头对完整存档有效并影响所有后续文件。 出于可移植性的原因,pax 标头中的所有数据都以 UTF-8 编码。

还有一些 tar 格式的变体可以读取,但不能创建:

  • 古老的 V7 格式。 这是 Unix 第七版的第一个 tar 格式,仅存储常规文件和目录。 名称不得超过 100 个字符,没有用户/组名称信息。 如果字段包含非 ASCII 字符,某些存档会错误计算标头校验和。
  • SunOS tar 扩展格式。 此格式是 POSIX.1-2001 pax 格式的变体,但不兼容。


Unicode 问题

tar 格式最初的构想是在磁带驱动器上进行备份,主要侧重于保留文件系统信息。 如今,tar 档案通常用于文件分发和通过网络交换档案。 原始格式(它是所有其他格式的基础)的一个问题是没有支持不同字符编码的概念。 例如,在 UTF-8 系统上创建的普通 tar 存档如果包含非 ASCII 字符,则无法在 Latin-1 系统上正确读取。 文本元数据(如文件名、链接名、用户/组名)将出现损坏。 不幸的是,没有办法自动检测档案的编码。 pax 格式旨在解决这个问题。 它使用通用字符编码 UTF-8 存储非 ASCII 元数据。

tarfile 中字符转换的细节由 TarFile 类的 encodingerrors 关键字参数控制。

encoding 定义用于存档中元数据的字符编码。 默认值为 sys.getfilesystemencoding()'ascii' 作为后备。 根据档案是读取还是写入,元数据必须被解码或编码。 如果 encoding 设置不正确,此转换可能会失败。

errors 参数定义了如何处理无法转换的字符。 可能的值列在 错误处理程序 部分。 默认方案是 'surrogateescape',Python 也使用它进行文件系统调用,请参阅 文件名、命令行参数和环境变量

对于 PAX_FORMAT 档案(默认),通常不需要 encoding,因为所有元数据都使用 UTF-8 存储。 encoding 仅用于在解码二进制 pax 标头或存储具有代理字符的字符串时的极少数情况。