rest25/library/tarfile.rst => rest262/library/tarfile.rst
n1+.. _tarfile-mod:
1
2:mod:`tarfile` --- Read and write tar archive files
3===================================================
4
5.. module:: tarfile
6   :synopsis: Read and write tar-format archive files.
7
8
9.. versionadded:: 2.3
10
11.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
12.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
13
14
n15-The :mod:`tarfile` module makes it possible to read and create tar archives.
n16+The :mod:`tarfile` module makes it possible to read and write tar
17+archives, including those using gzip or bz2 compression.
18+(:file:`.zip` files can be read and written using the :mod:`zipfile` module.)
19+ 
16Some facts and figures:
17
n18-* reads and writes :mod:`gzip` and :mod:`bzip2` compressed archives.
n22+* reads and writes :mod:`gzip` and :mod:`bz2` compressed archives.
19
n20-* creates POSIX 1003.1-1990 compliant or GNU tar compatible archives.
n24+* read/write support for the POSIX.1-1988 (ustar) format.
21
n22-* reads GNU tar extensions *longname*, *longlink* and *sparse*.
n26+* read/write support for the GNU tar format including *longname* and *longlink*
27+  extensions, read-only support for the *sparse* extension.
23
n24-* stores pathnames of unlimited length using GNU tar extensions.
n29+* read/write support for the POSIX.1-2001 (pax) format.
30+ 
31+  .. versionadded:: 2.6
25
26* handles directories, regular files, hardlinks, symbolic links, fifos,
27  character devices and block devices and is able to acquire and restore file
28  information like timestamp, access permissions and owner.
29
n30-* can handle tape devices.
31
n32- 
n38+.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
33-.. function:: open([name[, mode [, fileobj[, bufsize]]]])
34
35   Return a :class:`TarFile` object for the pathname *name*. For detailed
n36-   information on :class:`TarFile` objects, see TarFile Objects (section
n41+   information on :class:`TarFile` objects and the keyword arguments that are
37-   :ref:`tarfile-objects`).
42+   allowed, see :ref:`tarfile-objects`.
38
39   *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
40   to ``'r'``. Here is a full list of mode combinations:
41
n42-   +------------------+------------------------------------------+
n47+   +------------------+---------------------------------------------+
43-   | mode             | action                                   |
48+   | mode             | action                                      |
44-   +==================+==========================================+
49+   +==================+=============================================+
45-   | ``'r' or 'r:*'`` | Open for reading with transparent        |
50+   | ``'r' or 'r:*'`` | Open for reading with transparent           |
46-   |                  | compression (recommended).               |
51+   |                  | compression (recommended).                  |
47-   +------------------+------------------------------------------+
52+   +------------------+---------------------------------------------+
48-   | ``'r:'``         | Open for reading exclusively without     |
53+   | ``'r:'``         | Open for reading exclusively without        |
49-   |                  | compression.                             |
54+   |                  | compression.                                |
50-   +------------------+------------------------------------------+
55+   +------------------+---------------------------------------------+
51-   | ``'r:gz'``       | Open for reading with gzip compression.  |
56+   | ``'r:gz'``       | Open for reading with gzip compression.     |
52-   +------------------+------------------------------------------+
57+   +------------------+---------------------------------------------+
53-   | ``'r:bz2'``      | Open for reading with bzip2 compression. |
58+   | ``'r:bz2'``      | Open for reading with bzip2 compression.    |
54-   +------------------+------------------------------------------+
59+   +------------------+---------------------------------------------+
55-   | ``'a' or 'a:'``  | Open for appending with no compression.  |
60+   | ``'a' or 'a:'``  | Open for appending with no compression. The |
61+   |                  | file is created if it does not exist.       |
56-   +------------------+------------------------------------------+
62+   +------------------+---------------------------------------------+
57-   | ``'w' or 'w:'``  | Open for uncompressed writing.           |
63+   | ``'w' or 'w:'``  | Open for uncompressed writing.              |
58-   +------------------+------------------------------------------+
64+   +------------------+---------------------------------------------+
59-   | ``'w:gz'``       | Open for gzip compressed writing.        |
65+   | ``'w:gz'``       | Open for gzip compressed writing.           |
60-   +------------------+------------------------------------------+
66+   +------------------+---------------------------------------------+
61-   | ``'w:bz2'``      | Open for bzip2 compressed writing.       |
67+   | ``'w:bz2'``      | Open for bzip2 compressed writing.          |
62-   +------------------+------------------------------------------+
68+   +------------------+---------------------------------------------+
63
64   Note that ``'a:gz'`` or ``'a:bz2'`` is not possible. If *mode* is not suitable
65   to open a certain (compressed) file for reading, :exc:`ReadError` is raised. Use
66   *mode* ``'r'`` to avoid this.  If a compression method is not supported,
67   :exc:`CompressionError` is raised.
68
69   If *fileobj* is specified, it is used as an alternative to a file object opened
n70-   for *name*.
n76+   for *name*. It is supposed to be at position 0.
71
72   For special purposes, there is a second format for *mode*:
n73-   ``'filemode|[compression]'``.  :func:`open` will return a :class:`TarFile`
n79+   ``'filemode|[compression]'``.  :func:`tarfile.open` will return a :class:`TarFile`
74-   object that processes its data as a stream of blocks.  No random seeking will be
80+   object that processes its data as a stream of blocks.  No random seeking will
75-   done on the file. If given, *fileobj* may be any object that has a :meth:`read`
81+   be done on the file. If given, *fileobj* may be any object that has a
76-   or :meth:`write` method (depending on the *mode*). *bufsize* specifies the
82+   :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
77-   blocksize and defaults to ``20 * 512`` bytes. Use this variant in combination
83+   specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
78-   with e.g. ``sys.stdin``, a socket file object or a tape device. However, such a
84+   in combination with e.g. ``sys.stdin``, a socket file object or a tape
79-   :class:`TarFile` object is limited in that it does not allow to be accessed
85+   device. However, such a :class:`TarFile` object is limited in that it does
80-   randomly, see "Examples" (section :ref:`tar-examples`).  The currently possible
86+   not allow to be accessed randomly, see :ref:`tar-examples`.  The currently
81-   modes:
87+   possible modes:
82
83   +-------------+--------------------------------------------+
84   | Mode        | Action                                     |
85   +=============+============================================+
86   | ``'r|*'``   | Open a *stream* of tar blocks for reading  |
87   |             | with transparent compression.              |
88   +-------------+--------------------------------------------+
89   | ``'r|'``    | Open a *stream* of uncompressed tar blocks |
103   | ``'w|bz2'`` | Open an bzip2 compressed *stream* for      |
104   |             | writing.                                   |
105   +-------------+--------------------------------------------+
106
107
108.. class:: TarFile
109
110   Class for reading and writing tar archives. Do not use this class directly,
n111-   better use :func:`open` instead. See "TarFile Objects" (section
n117+   better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
112-   :ref:`tarfile-objects`).
113
114
115.. function:: is_tarfile(name)
116
117   Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
118   module can read.
119
120
n121-.. class:: TarFileCompat(filename[, mode[, compression]])
n126+.. class:: TarFileCompat(filename, mode='r', compression=TAR_PLAIN)
122
123   Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
124   Please consult the documentation of the :mod:`zipfile` module for more details.
125   *compression* must be one of the following constants:
126
127
128   .. data:: TAR_PLAIN
129
130      Constant for an uncompressed tar archive.
131
132
133   .. data:: TAR_GZIPPED
134
135      Constant for a :mod:`gzip` compressed tar archive.
136
137
n143+   .. deprecated:: 2.6
144+      The :class:`TarFileCompat` class has been deprecated for removal in Python 3.0.
145+ 
146+ 
138.. exception:: TarError
139
140   Base class for all :mod:`tarfile` exceptions.
141
142
143.. exception:: ReadError
144
145   Is raised when a tar archive is opened, that either cannot be handled by the
155.. exception:: StreamError
156
157   Is raised for the limitations that are typical for stream-like :class:`TarFile`
158   objects.
159
160
161.. exception:: ExtractError
162
n163-   Is raised for *non-fatal* errors when using :meth:`extract`, but only if
n172+   Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
164   :attr:`TarFile.errorlevel`\ ``== 2``.
n174+ 
175+ 
176+.. exception:: HeaderError
177+ 
178+   Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.
179+ 
180+   .. versionadded:: 2.6
181+ 
182+ 
183+Each of the following constants defines a tar archive format that the
184+:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
185+details.
186+ 
187+ 
188+.. data:: USTAR_FORMAT
189+ 
190+   POSIX.1-1988 (ustar) format.
191+ 
192+ 
193+.. data:: GNU_FORMAT
194+ 
195+   GNU tar format.
196+ 
197+ 
198+.. data:: PAX_FORMAT
199+ 
200+   POSIX.1-2001 (pax) format.
201+ 
202+ 
203+.. data:: DEFAULT_FORMAT
204+ 
205+   The default format for creating archives. This is currently :const:`GNU_FORMAT`.
206+ 
207+ 
208+The following variables are available on module level:
209+ 
210+ 
211+.. data:: ENCODING
212+ 
213+   The default character encoding i.e. the value from either
214+   :func:`sys.getfilesystemencoding` or :func:`sys.getdefaultencoding`.
165
166
167.. seealso::
168
169   Module :mod:`zipfile`
170      Documentation of the :mod:`zipfile` standard module.
171
n172-   `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/tar_134.html#SEC134>`_
n222+   `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
173      Documentation for tar archive files, including GNU tar extensions.
n174- 
175-.. % -----------------
176-.. % TarFile Objects
177-.. % -----------------
178
179
180.. _tarfile-objects:
181
182TarFile Objects
183---------------
184
185The :class:`TarFile` object provides an interface to a tar archive. A tar
186archive is a sequence of blocks. An archive member (a stored file) is made up of
n187-a header block followed by data blocks. It is possible, to store a file in a tar
n233+a header block followed by data blocks. It is possible to store a file in a tar
188archive several times. Each archive member is represented by a :class:`TarInfo`
n189-object, see TarInfo Objects (section :ref:`tarinfo-objects`) for details.
n235+object, see :ref:`tarinfo-objects` for details.
190
191
n192-.. class:: TarFile([name [, mode[, fileobj]]])
n238+.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0)
193
n194-   Open an *(uncompressed)* tar archive *name*. *mode* is either ``'r'`` to read
n240+   All following arguments are optional and can be accessed as instance attributes
195-   from an existing archive, ``'a'`` to append data to an existing file or ``'w'``
241+   as well.
196-   to create a new file overwriting an existing one. *mode* defaults to ``'r'``.
242+ 
243+   *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
244+   In this case, the file object's :attr:`name` attribute is used if it exists.
245+ 
246+   *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
247+   data to an existing file or ``'w'`` to create a new file overwriting an existing
248+   one.
197
198   If *fileobj* is given, it is used for reading or writing data. If it can be
n199-   determined, *mode* is overridden by *fileobj*'s mode.
n251+   determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
252+   from position 0.
200
201   .. note::
202
203      *fileobj* is not closed, when :class:`TarFile` is closed.
204
n258+   *format* controls the archive format. It must be one of the constants
259+   :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
260+   defined at module level.
261+ 
262+   .. versionadded:: 2.6
263+ 
264+   The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
265+   with a different one.
266+ 
267+   .. versionadded:: 2.6
268+ 
269+   If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
270+   is :const:`True`, add the content of the target files to the archive. This has no
271+   effect on systems that do not support symbolic links.
272+ 
273+   If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
274+   If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
275+   as possible. This is only useful for reading concatenated or damaged archives.
276+ 
277+   *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
278+   messages). The messages are written to ``sys.stderr``.
279+ 
280+   If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
281+   Nevertheless, they appear as error messages in the debug output, when debugging
282+   is enabled.  If ``1``, all *fatal* errors are raised as :exc:`OSError` or
283+   :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
284+   :exc:`TarError` exceptions as well.
285+ 
286+   The *encoding* and *errors* arguments control the way strings are converted to
287+   unicode objects and vice versa. The default settings will work for most users.
288+   See section :ref:`tar-unicode` for in-depth information.
289+ 
290+   .. versionadded:: 2.6
291+ 
292+   The *pax_headers* argument is an optional dictionary of unicode strings which
293+   will be added as a pax global header if *format* is :const:`PAX_FORMAT`.
294+ 
295+   .. versionadded:: 2.6
296+ 
205
206.. method:: TarFile.open(...)
207
n208-   Alternative constructor. The :func:`open` function on module level is actually a
n300+   Alternative constructor. The :func:`tarfile.open` function is actually a
209-   shortcut to this classmethod. See section :ref:`module-tarfile` for details.
301+   shortcut to this classmethod.
210
211
212.. method:: TarFile.getmember(name)
213
214   Return a :class:`TarInfo` object for member *name*. If *name* can not be found
215   in the archive, :exc:`KeyError` is raised.
216
217   .. note::
237   Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
238   only the names of the members are printed. If it is :const:`True`, output
239   similar to that of :program:`ls -l` is produced.
240
241
242.. method:: TarFile.next()
243
244   Return the next member of the archive as a :class:`TarInfo` object, when
n245-   :class:`TarFile` is opened for reading. Return ``None`` if there is no more
n337+   :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
246   available.
247
248
n249-.. method:: TarFile.extractall([path[, members]])
n341+.. method:: TarFile.extractall(path=".", members=None)
250
251   Extract all members from the archive to the current working directory or
252   directory *path*. If optional *members* is given, it must be a subset of the
n253-   list returned by :meth:`getmembers`. Directory informations like owner,
n345+   list returned by :meth:`getmembers`. Directory information like owner,
254   modification time and permissions are set after all members have been extracted.
255   This is done to work around two problems: A directory's modification time is
256   reset each time a file is created in it. And, if a directory's permissions do
257   not allow writing, extracting files to it will fail.
258
n351+   .. warning::
352+ 
353+      Never extract archives from untrusted sources without prior inspection.
354+      It is possible that files are created outside of *path*, e.g. members
355+      that have absolute filenames starting with ``"/"`` or filenames with two
356+      dots ``".."``.
357+ 
259   .. versionadded:: 2.5
260
261
n262-.. method:: TarFile.extract(member[, path])
n361+.. method:: TarFile.extract(member, path="")
263
264   Extract a member from the archive to the current working directory, using its
265   full name. Its file information is extracted as accurately as possible. *member*
266   may be a filename or a :class:`TarInfo` object. You can specify a different
267   directory using *path*.
268
269   .. note::
270
n271-      Because the :meth:`extract` method allows random access to a tar archive there
n370+      The :meth:`extract` method does not take care of several extraction issues.
272-      are some issues you must take care of yourself. See the description for
371+      In most cases you should consider using the :meth:`extractall` method.
273-      :meth:`extractall` above.
372+ 
373+   .. warning::
374+ 
375+      See the warning for :meth:`extractall`.
274
275
276.. method:: TarFile.extractfile(member)
277
278   Extract a member from the archive as a file object. *member* may be a filename
279   or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
280   is returned. If *member* is a link, a file-like object is constructed from the
n281-   link's target. If *member* is none of the above, ``None`` is returned.
n383+   link's target. If *member* is none of the above, :const:`None` is returned.
282
283   .. note::
284
285      The file-like object is read-only and provides the following methods:
286      :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`.
287
288
n289-.. method:: TarFile.add(name[, arcname[, recursive]])
n391+.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None)
290
291   Add the file *name* to the archive. *name* may be any type of file (directory,
292   fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
293   for the file in the archive. Directories are added recursively by default. This
n294-   can be avoided by setting *recursive* to :const:`False`; the default is
n396+   can be avoided by setting *recursive* to :const:`False`. If *exclude* is given
295-   :const:`True`.
397+   it must be a function that takes one filename argument and returns a boolean
398+   value. Depending on this value the respective file is either excluded
399+   (:const:`True`) or added (:const:`False`).
296
n401+   .. versionchanged:: 2.6
402+      Added the *exclude* parameter.
297
n404+ 
298-.. method:: TarFile.addfile(tarinfo[, fileobj])
405+.. method:: TarFile.addfile(tarinfo, fileobj=None)
299
300   Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
301   ``tarinfo.size`` bytes are read from it and added to the archive.  You can
302   create :class:`TarInfo` objects using :meth:`gettarinfo`.
303
304   .. note::
305
306      On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
307      avoid irritation about the file size.
308
309
n310-.. method:: TarFile.gettarinfo([name[, arcname[, fileobj]]])
n417+.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
311
312   Create a :class:`TarInfo` object for either the file *name* or the file object
313   *fileobj* (using :func:`os.fstat` on its file descriptor).  You can modify some
314   of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
315   If given, *arcname* specifies an alternative name for the file in the archive.
316
317
318.. method:: TarFile.close()
319
320   Close the :class:`TarFile`. In write mode, two finishing zero blocks are
321   appended to the archive.
322
323
324.. attribute:: TarFile.posix
325
n326-   If true, create a POSIX 1003.1-1990 compliant archive. GNU extensions are not
n433+   Setting this to :const:`True` is equivalent to setting the :attr:`format`
327-   used, because they are not part of the POSIX standard.  This limits the length
434+   attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to
328-   of filenames to at most 256, link names to 100 characters and the maximum file
435+   :const:`GNU_FORMAT`.
329-   size to 8 gigabytes. A :exc:`ValueError` is raised if a file exceeds this limit.
330-   If false, create a GNU tar compatible archive.  It will not be POSIX compliant,
331-   but can store files without any of the above restrictions.
332
333   .. versionchanged:: 2.4
334      *posix* defaults to :const:`False`.
335
n440+   .. deprecated:: 2.6
441+      Use the :attr:`format` attribute instead.
336
n337-.. attribute:: TarFile.dereference
338
n339-   If false, add symbolic and hard links to archive. If true, add the content of
340-   the target files to the archive.  This has no effect on systems that do not
341-   support symbolic links.
342- 
343- 
344-.. attribute:: TarFile.ignore_zeros
444+.. attribute:: TarFile.pax_headers
345
n346-   If false, treat an empty block as the end of the archive. If true, skip empty
n446+   A dictionary containing key-value pairs of pax global headers.
347-   (and invalid) blocks and try to get as many members as possible. This is only
348-   useful for concatenated or damaged archives.
349
n350- 
n448+   .. versionadded:: 2.6
351-.. attribute:: TarFile.debug=0
352- 
353-   To be set from ``0`` (no debug messages; the default) up to ``3`` (all debug
354-   messages). The messages are written to ``sys.stderr``.
355- 
356- 
357-.. attribute:: TarFile.errorlevel
358- 
359-   If ``0`` (the default), all errors are ignored when using :meth:`extract`.
360-   Nevertheless, they appear as error messages in the debug output, when debugging
361-   is enabled.  If ``1``, all *fatal* errors are raised as :exc:`OSError` or
362-   :exc:`IOError` exceptions.  If ``2``, all *non-fatal* errors are raised as
363-   :exc:`TarError` exceptions as well.
364- 
365-.. % -----------------
366-.. % TarInfo Objects
367-.. % -----------------
368
369
370.. _tarinfo-objects:
371
372TarInfo Objects
373---------------
374
375A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
376from storing all required attributes of a file (like file type, size, time,
377permissions, owner etc.), it provides some useful methods to determine its type.
378It does *not* contain the file's data itself.
379
380:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
381:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
382
383
n384-.. class:: TarInfo([name])
n465+.. class:: TarInfo(name="")
385
386   Create a :class:`TarInfo` object.
387
388
n389-.. method:: TarInfo.frombuf()
n470+.. method:: TarInfo.frombuf(buf)
390
n391-   Create and return a :class:`TarInfo` object from a string buffer.
n472+   Create and return a :class:`TarInfo` object from string buffer *buf*.
392
n393- 
394-.. method:: TarInfo.tobuf(posix)
395- 
396-   Create a string buffer from a :class:`TarInfo` object. See :class:`TarFile`'s
397-   :attr:`posix` attribute for information on the *posix* argument. It defaults to
398-   :const:`False`.
399- 
400-   .. versionadded:: 2.5
474+   .. versionadded:: 2.6
401-      The *posix* parameter.
475+      Raises :exc:`HeaderError` if the buffer is invalid..
476+ 
477+ 
478+.. method:: TarInfo.fromtarfile(tarfile)
479+ 
480+   Read the next member from the :class:`TarFile` object *tarfile* and return it as
481+   a :class:`TarInfo` object.
482+ 
483+   .. versionadded:: 2.6
484+ 
485+ 
486+.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict')
487+ 
488+   Create a string buffer from a :class:`TarInfo` object. For information on the
489+   arguments see the constructor of the :class:`TarFile` class.
490+ 
491+   .. versionchanged:: 2.6
492+      The arguments were added.
402
403A ``TarInfo`` object has the following public data attributes:
404
405
406.. attribute:: TarInfo.name
407
408   Name of the archive member.
409
452
453   User name.
454
455
456.. attribute:: TarInfo.gname
457
458   Group name.
459
n551+ 
552+.. attribute:: TarInfo.pax_headers
553+ 
554+   A dictionary containing key-value pairs of an associated pax extended header.
555+ 
556+   .. versionadded:: 2.6
557+ 
460A :class:`TarInfo` object also provides some convenient query methods:
461
462
463.. method:: TarInfo.isfile()
464
465   Return :const:`True` if the :class:`Tarinfo` object is a regular file.
466
467
498.. method:: TarInfo.isfifo()
499
500   Return :const:`True` if it is a FIFO.
501
502
503.. method:: TarInfo.isdev()
504
505   Return :const:`True` if it is one of character device, block device or FIFO.
n506- 
507-.. % ------------------------
508-.. % Examples
509-.. % ------------------------
510
511
512.. _tar-examples:
513
514Examples
515--------
516
517How to extract an entire tar archive to the current working directory::
518
519   import tarfile
520   tar = tarfile.open("sample.tar.gz")
521   tar.extractall()
n616+   tar.close()
617+ 
618+How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
619+a generator function instead of a list::
620+ 
621+   import os
622+   import tarfile
623+ 
624+   def py_files(members):
625+       for tarinfo in members:
626+           if os.path.splitext(tarinfo.name)[1] == ".py":
627+               yield tarinfo
628+ 
629+   tar = tarfile.open("sample.tar.gz")
630+   tar.extractall(members=py_files(tar))
522   tar.close()
523
524How to create an uncompressed tar archive from a list of filenames::
525
526   import tarfile
527   tar = tarfile.open("sample.tar", "w")
528   for name in ["foo", "bar", "quux"]:
529       tar.add(name)
538       if tarinfo.isreg():
539           print "a regular file."
540       elif tarinfo.isdir():
541           print "a directory."
542       else:
543           print "something else."
544   tar.close()
545
n546-How to create a tar archive with faked information::
547
n548-   import tarfile
n656+.. _tar-formats:
549-   tar = tarfile.open("sample.tar.gz", "w:gz")
550-   for name in namelist:
551-       tarinfo = tar.gettarinfo(name, "fakeproj-1.0/" + name)
552-       tarinfo.uid = 123
553-       tarinfo.gid = 456
554-       tarinfo.uname = "johndoe"
555-       tarinfo.gname = "fake"
556-       tar.addfile(tarinfo, file(name))
557-   tar.close()
558
n559-The *only* way to extract an uncompressed tar stream from ``sys.stdin``::
n658+Supported tar formats
659+---------------------
560
n561-   import sys
n661+There are three tar formats that can be created with the :mod:`tarfile` module:
562-   import tarfile
563-   tar = tarfile.open(mode="r|", fileobj=sys.stdin)
564-   for tarinfo in tar:
565-       tar.extract(tarinfo)
566-   tar.close()
567
t663+* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
664+  up to a length of at best 256 characters and linknames up to 100 characters. The
665+  maximum file size is 8 gigabytes. This is an old and limited but widely
666+  supported format.
667+ 
668+* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
669+  linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
670+  standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
671+  extensions for long names, sparse file support is read-only.
672+ 
673+* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
674+  format with virtually no limits. It supports long filenames and linknames, large
675+  files and stores pathnames in a portable way. However, not all tar
676+  implementations today are able to handle pax archives properly.
677+ 
678+  The *pax* format is an extension to the existing *ustar* format. It uses extra
679+  headers for information that cannot be stored otherwise. There are two flavours
680+  of pax headers: Extended headers only affect the subsequent file header, global
681+  headers are valid for the complete archive and affect all following files. All
682+  the data in a pax header is encoded in *UTF-8* for portability reasons.
683+ 
684+There are some more variants of the tar format which can be read, but not
685+created:
686+ 
687+* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
688+  storing only regular files and directories. Names must not be longer than 100
689+  characters, there is no user/group name information. Some archives have
690+  miscalculated header checksums in case of fields with non-ASCII characters.
691+ 
692+* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
693+  pax format, but is not compatible.
694+ 
695+.. _tar-unicode:
696+ 
697+Unicode issues
698+--------------
699+ 
700+The tar format was originally conceived to make backups on tape drives with the
701+main focus on preserving file system information. Nowadays tar archives are
702+commonly used for file distribution and exchanging archives over networks. One
703+problem of the original format (that all other formats are merely variants of)
704+is that there is no concept of supporting different character encodings. For
705+example, an ordinary tar archive created on a *UTF-8* system cannot be read
706+correctly on a *Latin-1* system if it contains non-ASCII characters. Names (i.e.
707+filenames, linknames, user/group names) containing these characters will appear
708+damaged.  Unfortunately, there is no way to autodetect the encoding of an
709+archive.
710+ 
711+The pax format was designed to solve this problem. It stores non-ASCII names
712+using the universal character encoding *UTF-8*. When a pax archive is read,
713+these *UTF-8* names are converted to the encoding of the local file system.
714+ 
715+The details of unicode conversion are controlled by the *encoding* and *errors*
716+keyword arguments of the :class:`TarFile` class.
717+ 
718+The default value for *encoding* is the local character encoding. It is deduced
719+from :func:`sys.getfilesystemencoding` and :func:`sys.getdefaultencoding`. In
720+read mode, *encoding* is used exclusively to convert unicode names from a pax
721+archive to strings in the local character encoding. In write mode, the use of
722+*encoding* depends on the chosen archive format. In case of :const:`PAX_FORMAT`,
723+input names that contain non-ASCII characters need to be decoded before being
724+stored as *UTF-8* strings. The other formats do not make use of *encoding*
725+unless unicode objects are used as input names. These are converted to 8-bit
726+character strings before they are added to the archive.
727+ 
728+The *errors* argument defines how characters are treated that cannot be
729+converted to or from *encoding*. Possible values are listed in section
730+:ref:`codec-base-classes`. In read mode, there is an additional scheme
731+``'utf-8'`` which means that bad characters are replaced by their *UTF-8*
732+representation. This is the default scheme. In write mode the default value for
733+*errors* is ``'strict'`` to ensure that name information is not altered
734+unnoticed.
735+ 
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op