blob: 3adb6331038daa8b4c822b01b35b4c3a1e6e5aa9 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`tarfile` --- Read and write tar archive files
2===================================================
3
4.. module:: tarfile
5 :synopsis: Read and write tar-format archive files.
6
7
Georg Brandl116aa622007-08-15 14:28:22 +00008.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
9.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
10
Raymond Hettingera1993682011-01-27 01:20:32 +000011**Source code:** :source:`Lib/tarfile.py`
12
13--------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Guido van Rossum77677112007-11-05 19:43:04 +000015The :mod:`tarfile` module makes it possible to read and write tar
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010016archives, including those using gzip, bz2 and lzma compression.
Éric Araujof2fbb9c2012-01-16 16:55:55 +010017Use the :mod:`zipfile` module to read or write :file:`.zip` files, or the
18higher-level functions in :ref:`shutil <archiving-operations>`.
Guido van Rossum77677112007-11-05 19:43:04 +000019
Georg Brandl116aa622007-08-15 14:28:22 +000020Some facts and figures:
21
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010022* reads and writes :mod:`gzip`, :mod:`bz2` and :mod:`lzma` compressed archives.
Georg Brandl116aa622007-08-15 14:28:22 +000023
24* read/write support for the POSIX.1-1988 (ustar) format.
25
26* read/write support for the GNU tar format including *longname* and *longlink*
Lars Gustäbel9cbdd752010-10-29 09:08:19 +000027 extensions, read-only support for all variants of the *sparse* extension
28 including restoration of sparse files.
Georg Brandl116aa622007-08-15 14:28:22 +000029
30* read/write support for the POSIX.1-2001 (pax) format.
31
Georg Brandl116aa622007-08-15 14:28:22 +000032* handles directories, regular files, hardlinks, symbolic links, fifos,
33 character devices and block devices and is able to acquire and restore file
34 information like timestamp, access permissions and owner.
35
Lars Gustäbel521dfb02011-12-12 10:22:56 +010036.. versionchanged:: 3.3
37 Added support for :mod:`lzma` compression.
38
Georg Brandl116aa622007-08-15 14:28:22 +000039
Benjamin Petersona37cfc62008-05-26 13:48:34 +000040.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +000041
42 Return a :class:`TarFile` object for the pathname *name*. For detailed
43 information on :class:`TarFile` objects and the keyword arguments that are
44 allowed, see :ref:`tarfile-objects`.
45
46 *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
47 to ``'r'``. Here is a full list of mode combinations:
48
49 +------------------+---------------------------------------------+
50 | mode | action |
51 +==================+=============================================+
52 | ``'r' or 'r:*'`` | Open for reading with transparent |
53 | | compression (recommended). |
54 +------------------+---------------------------------------------+
55 | ``'r:'`` | Open for reading exclusively without |
56 | | compression. |
57 +------------------+---------------------------------------------+
58 | ``'r:gz'`` | Open for reading with gzip compression. |
59 +------------------+---------------------------------------------+
60 | ``'r:bz2'`` | Open for reading with bzip2 compression. |
61 +------------------+---------------------------------------------+
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010062 | ``'r:xz'`` | Open for reading with lzma compression. |
63 +------------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +000064 | ``'a' or 'a:'`` | Open for appending with no compression. The |
65 | | file is created if it does not exist. |
66 +------------------+---------------------------------------------+
67 | ``'w' or 'w:'`` | Open for uncompressed writing. |
68 +------------------+---------------------------------------------+
69 | ``'w:gz'`` | Open for gzip compressed writing. |
70 +------------------+---------------------------------------------+
71 | ``'w:bz2'`` | Open for bzip2 compressed writing. |
72 +------------------+---------------------------------------------+
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010073 | ``'w:xz'`` | Open for lzma compressed writing. |
74 +------------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +000075
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +010076 Note that ``'a:gz'``, ``'a:bz2'`` or ``'a:xz'`` is not possible. If *mode*
77 is not suitable to open a certain (compressed) file for reading,
78 :exc:`ReadError` is raised. Use *mode* ``'r'`` to avoid this. If a
79 compression method is not supported, :exc:`CompressionError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +000080
Antoine Pitrou11cb9612010-09-15 11:11:28 +000081 If *fileobj* is specified, it is used as an alternative to a :term:`file object`
82 opened in binary mode for *name*. It is supposed to be at position 0.
Georg Brandl116aa622007-08-15 14:28:22 +000083
Benjamin Peterson9b2731b2014-06-07 12:45:37 -070084 For modes ``'w:gz'``, ``'r:gz'``, ``'w:bz2'``, ``'r:bz2'``, :func:`tarfile.open`
85 accepts the keyword argument *compresslevel* to specify the compression level of
86 the file.
87
Georg Brandl116aa622007-08-15 14:28:22 +000088 For special purposes, there is a second format for *mode*:
Benjamin Petersona37cfc62008-05-26 13:48:34 +000089 ``'filemode|[compression]'``. :func:`tarfile.open` will return a :class:`TarFile`
Georg Brandl116aa622007-08-15 14:28:22 +000090 object that processes its data as a stream of blocks. No random seeking will
91 be done on the file. If given, *fileobj* may be any object that has a
92 :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
93 specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
Antoine Pitrou11cb9612010-09-15 11:11:28 +000094 in combination with e.g. ``sys.stdin``, a socket :term:`file object` or a tape
Georg Brandl116aa622007-08-15 14:28:22 +000095 device. However, such a :class:`TarFile` object is limited in that it does
96 not allow to be accessed randomly, see :ref:`tar-examples`. The currently
97 possible modes:
98
99 +-------------+--------------------------------------------+
100 | Mode | Action |
101 +=============+============================================+
102 | ``'r|*'`` | Open a *stream* of tar blocks for reading |
103 | | with transparent compression. |
104 +-------------+--------------------------------------------+
105 | ``'r|'`` | Open a *stream* of uncompressed tar blocks |
106 | | for reading. |
107 +-------------+--------------------------------------------+
108 | ``'r|gz'`` | Open a gzip compressed *stream* for |
109 | | reading. |
110 +-------------+--------------------------------------------+
111 | ``'r|bz2'`` | Open a bzip2 compressed *stream* for |
112 | | reading. |
113 +-------------+--------------------------------------------+
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100114 | ``'r|xz'`` | Open a lzma compressed *stream* for |
115 | | reading. |
116 +-------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000117 | ``'w|'`` | Open an uncompressed *stream* for writing. |
118 +-------------+--------------------------------------------+
Lars Gustäbel0c6cbbd2011-12-10 12:45:45 +0100119 | ``'w|gz'`` | Open a gzip compressed *stream* for |
Georg Brandl116aa622007-08-15 14:28:22 +0000120 | | writing. |
121 +-------------+--------------------------------------------+
Lars Gustäbel0c6cbbd2011-12-10 12:45:45 +0100122 | ``'w|bz2'`` | Open a bzip2 compressed *stream* for |
Georg Brandl116aa622007-08-15 14:28:22 +0000123 | | writing. |
124 +-------------+--------------------------------------------+
Lars Gustäbel0a9dd2f2011-12-10 20:38:14 +0100125 | ``'w|xz'`` | Open an lzma compressed *stream* for |
126 | | writing. |
127 +-------------+--------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129
130.. class:: TarFile
131
132 Class for reading and writing tar archives. Do not use this class directly,
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000133 better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135
136.. function:: is_tarfile(name)
137
138 Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
139 module can read.
140
141
Lars Gustäbel0c24e8b2008-08-02 11:43:24 +0000142The :mod:`tarfile` module defines the following exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144
145.. exception:: TarError
146
147 Base class for all :mod:`tarfile` exceptions.
148
149
150.. exception:: ReadError
151
152 Is raised when a tar archive is opened, that either cannot be handled by the
153 :mod:`tarfile` module or is somehow invalid.
154
155
156.. exception:: CompressionError
157
158 Is raised when a compression method is not supported or when the data cannot be
159 decoded properly.
160
161
162.. exception:: StreamError
163
164 Is raised for the limitations that are typical for stream-like :class:`TarFile`
165 objects.
166
167
168.. exception:: ExtractError
169
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000170 Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
Georg Brandl116aa622007-08-15 14:28:22 +0000171 :attr:`TarFile.errorlevel`\ ``== 2``.
172
173
174.. exception:: HeaderError
175
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000176 Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.
177
Georg Brandl116aa622007-08-15 14:28:22 +0000178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180Each of the following constants defines a tar archive format that the
181:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
182details.
183
184
185.. data:: USTAR_FORMAT
186
187 POSIX.1-1988 (ustar) format.
188
189
190.. data:: GNU_FORMAT
191
192 GNU tar format.
193
194
195.. data:: PAX_FORMAT
196
197 POSIX.1-2001 (pax) format.
198
199
200.. data:: DEFAULT_FORMAT
201
202 The default format for creating archives. This is currently :const:`GNU_FORMAT`.
203
204
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000205The following variables are available on module level:
206
207
208.. data:: ENCODING
209
Victor Stinner0f35e2c2010-06-11 23:46:47 +0000210 The default character encoding: ``'utf-8'`` on Windows,
211 :func:`sys.getfilesystemencoding` otherwise.
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000212
213
Georg Brandl116aa622007-08-15 14:28:22 +0000214.. seealso::
215
216 Module :mod:`zipfile`
217 Documentation of the :mod:`zipfile` standard module.
218
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000219 `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000220 Documentation for tar archive files, including GNU tar extensions.
221
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223.. _tarfile-objects:
224
225TarFile Objects
226---------------
227
228The :class:`TarFile` object provides an interface to a tar archive. A tar
229archive is a sequence of blocks. An archive member (a stored file) is made up of
230a header block followed by data blocks. It is possible to store a file in a tar
231archive several times. Each archive member is represented by a :class:`TarInfo`
232object, see :ref:`tarinfo-objects` for details.
233
Lars Gustäbel01385812010-03-03 12:08:54 +0000234A :class:`TarFile` object can be used as a context manager in a :keyword:`with`
235statement. It will automatically be closed when the block is completed. Please
236note that in the event of an exception an archive opened for writing will not
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000237be finalized; only the internally used file object will be closed. See the
Lars Gustäbel01385812010-03-03 12:08:54 +0000238:ref:`tar-examples` section for a use case.
239
240.. versionadded:: 3.2
241 Added support for the context manager protocol.
Georg Brandl116aa622007-08-15 14:28:22 +0000242
Victor Stinnerde629d42010-05-05 21:43:57 +0000243.. class:: 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)
Georg Brandl116aa622007-08-15 14:28:22 +0000244
245 All following arguments are optional and can be accessed as instance attributes
246 as well.
247
248 *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
249 In this case, the file object's :attr:`name` attribute is used if it exists.
250
251 *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
252 data to an existing file or ``'w'`` to create a new file overwriting an existing
253 one.
254
255 If *fileobj* is given, it is used for reading or writing data. If it can be
256 determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
257 from position 0.
258
259 .. note::
260
261 *fileobj* is not closed, when :class:`TarFile` is closed.
262
263 *format* controls the archive format. It must be one of the constants
264 :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
265 defined at module level.
266
Georg Brandl116aa622007-08-15 14:28:22 +0000267 The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
268 with a different one.
269
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000270 If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
271 is :const:`True`, add the content of the target files to the archive. This has no
Georg Brandl116aa622007-08-15 14:28:22 +0000272 effect on systems that do not support symbolic links.
273
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000274 If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
275 If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
Georg Brandl116aa622007-08-15 14:28:22 +0000276 as possible. This is only useful for reading concatenated or damaged archives.
277
278 *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
279 messages). The messages are written to ``sys.stderr``.
280
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000281 If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
Georg Brandl116aa622007-08-15 14:28:22 +0000282 Nevertheless, they appear as error messages in the debug output, when debugging
Antoine Pitrou62ab10a02011-10-12 20:10:51 +0200283 is enabled. If ``1``, all *fatal* errors are raised as :exc:`OSError`
284 exceptions. If ``2``, all *non-fatal* errors are raised as :exc:`TarError`
285 exceptions as well.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000287 The *encoding* and *errors* arguments define the character encoding to be
288 used for reading or writing the archive and how conversion errors are going
289 to be handled. The default settings will work for most users.
Georg Brandl116aa622007-08-15 14:28:22 +0000290 See section :ref:`tar-unicode` for in-depth information.
291
Victor Stinnerde629d42010-05-05 21:43:57 +0000292 .. versionchanged:: 3.2
293 Use ``'surrogateescape'`` as the default for the *errors* argument.
294
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000295 The *pax_headers* argument is an optional dictionary of strings which
Georg Brandl116aa622007-08-15 14:28:22 +0000296 will be added as a pax global header if *format* is :const:`PAX_FORMAT`.
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
Raymond Hettinger7096e262014-05-23 03:46:52 +0100299.. classmethod:: TarFile.open(...)
Georg Brandl116aa622007-08-15 14:28:22 +0000300
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000301 Alternative constructor. The :func:`tarfile.open` function is actually a
302 shortcut to this classmethod.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304
305.. method:: TarFile.getmember(name)
306
307 Return a :class:`TarInfo` object for member *name*. If *name* can not be found
308 in the archive, :exc:`KeyError` is raised.
309
310 .. note::
311
312 If a member occurs more than once in the archive, its last occurrence is assumed
313 to be the most up-to-date version.
314
315
316.. method:: TarFile.getmembers()
317
318 Return the members of the archive as a list of :class:`TarInfo` objects. The
319 list has the same order as the members in the archive.
320
321
322.. method:: TarFile.getnames()
323
324 Return the members as a list of their names. It has the same order as the list
325 returned by :meth:`getmembers`.
326
327
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +0300328.. method:: TarFile.list(verbose=True, *, members=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330 Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
331 only the names of the members are printed. If it is :const:`True`, output
Serhiy Storchakaa7eb7462014-08-21 10:01:16 +0300332 similar to that of :program:`ls -l` is produced. If optional *members* is
333 given, it must be a subset of the list returned by :meth:`getmembers`.
334
335 .. versionchanged:: 3.5
336 Added the *members* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338
339.. method:: TarFile.next()
340
341 Return the next member of the archive as a :class:`TarInfo` object, when
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000342 :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
Georg Brandl116aa622007-08-15 14:28:22 +0000343 available.
344
345
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000346.. method:: TarFile.extractall(path=".", members=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000347
348 Extract all members from the archive to the current working directory or
349 directory *path*. If optional *members* is given, it must be a subset of the
350 list returned by :meth:`getmembers`. Directory information like owner,
351 modification time and permissions are set after all members have been extracted.
352 This is done to work around two problems: A directory's modification time is
353 reset each time a file is created in it. And, if a directory's permissions do
354 not allow writing, extracting files to it will fail.
355
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000356 .. warning::
357
358 Never extract archives from untrusted sources without prior inspection.
359 It is possible that files are created outside of *path*, e.g. members
360 that have absolute filenames starting with ``"/"`` or filenames with two
361 dots ``".."``.
362
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000364.. method:: TarFile.extract(member, path="", set_attrs=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000365
366 Extract a member from the archive to the current working directory, using its
367 full name. Its file information is extracted as accurately as possible. *member*
368 may be a filename or a :class:`TarInfo` object. You can specify a different
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000369 directory using *path*. File attributes (owner, mtime, mode) are set unless
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200370 *set_attrs* is false.
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372 .. note::
373
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000374 The :meth:`extract` method does not take care of several extraction issues.
375 In most cases you should consider using the :meth:`extractall` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000377 .. warning::
378
379 See the warning for :meth:`extractall`.
380
Martin v. Löwis16f344d2010-11-01 21:39:13 +0000381 .. versionchanged:: 3.2
382 Added the *set_attrs* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +0000383
384.. method:: TarFile.extractfile(member)
385
386 Extract a member from the archive as a file object. *member* may be a filename
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200387 or a :class:`TarInfo` object. If *member* is a regular file or a link, an
388 :class:`io.BufferedReader` object is returned. Otherwise, :const:`None` is
389 returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
Lars Gustäbel7a919e92012-05-05 18:15:03 +0200391 .. versionchanged:: 3.3
392 Return an :class:`io.BufferedReader` object.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394
Raymond Hettingera63a3122011-01-26 20:34:14 +0000395.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Raymond Hettingera63a3122011-01-26 20:34:14 +0000397 Add the file *name* to the archive. *name* may be any type of file
398 (directory, fifo, symbolic link, etc.). If given, *arcname* specifies an
399 alternative name for the file in the archive. Directories are added
400 recursively by default. This can be avoided by setting *recursive* to
401 :const:`False`. If *exclude* is given, it must be a function that takes one
402 filename argument and returns a boolean value. Depending on this value the
403 respective file is either excluded (:const:`True`) or added
404 (:const:`False`). If *filter* is specified it must be a keyword argument. It
405 should be a function that takes a :class:`TarInfo` object argument and
406 returns the changed :class:`TarInfo` object. If it instead returns
407 :const:`None` the :class:`TarInfo` object will be excluded from the
408 archive. See :ref:`tar-examples` for an example.
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000409
410 .. versionchanged:: 3.2
411 Added the *filter* parameter.
412
413 .. deprecated:: 3.2
414 The *exclude* parameter is deprecated, please use the *filter* parameter
415 instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000418.. method:: TarFile.addfile(tarinfo, fileobj=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420 Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
421 ``tarinfo.size`` bytes are read from it and added to the archive. You can
422 create :class:`TarInfo` objects using :meth:`gettarinfo`.
423
424 .. note::
425
426 On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
427 avoid irritation about the file size.
428
429
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000430.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000431
Antoine Pitrou11cb9612010-09-15 11:11:28 +0000432 Create a :class:`TarInfo` object for either the file *name* or the :term:`file
433 object` *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify
434 some of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
Georg Brandl116aa622007-08-15 14:28:22 +0000435 If given, *arcname* specifies an alternative name for the file in the archive.
436
437
438.. method:: TarFile.close()
439
440 Close the :class:`TarFile`. In write mode, two finishing zero blocks are
441 appended to the archive.
442
443
Georg Brandl116aa622007-08-15 14:28:22 +0000444.. attribute:: TarFile.pax_headers
445
446 A dictionary containing key-value pairs of pax global headers.
447
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450.. _tarinfo-objects:
451
452TarInfo Objects
453---------------
454
455A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
456from storing all required attributes of a file (like file type, size, time,
457permissions, owner etc.), it provides some useful methods to determine its type.
458It does *not* contain the file's data itself.
459
460:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
461:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
462
463
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000464.. class:: TarInfo(name="")
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466 Create a :class:`TarInfo` object.
467
468
469.. method:: TarInfo.frombuf(buf)
470
471 Create and return a :class:`TarInfo` object from string buffer *buf*.
472
Georg Brandl55ac8f02007-09-01 13:51:09 +0000473 Raises :exc:`HeaderError` if the buffer is invalid..
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475
476.. method:: TarInfo.fromtarfile(tarfile)
477
478 Read the next member from the :class:`TarFile` object *tarfile* and return it as
479 a :class:`TarInfo` object.
480
Georg Brandl116aa622007-08-15 14:28:22 +0000481
Victor Stinnerde629d42010-05-05 21:43:57 +0000482.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='surrogateescape')
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484 Create a string buffer from a :class:`TarInfo` object. For information on the
485 arguments see the constructor of the :class:`TarFile` class.
486
Victor Stinnerde629d42010-05-05 21:43:57 +0000487 .. versionchanged:: 3.2
488 Use ``'surrogateescape'`` as the default for the *errors* argument.
489
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491A ``TarInfo`` object has the following public data attributes:
492
493
494.. attribute:: TarInfo.name
495
496 Name of the archive member.
497
498
499.. attribute:: TarInfo.size
500
501 Size in bytes.
502
503
504.. attribute:: TarInfo.mtime
505
506 Time of last modification.
507
508
509.. attribute:: TarInfo.mode
510
511 Permission bits.
512
513
514.. attribute:: TarInfo.type
515
516 File type. *type* is usually one of these constants: :const:`REGTYPE`,
517 :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
518 :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
519 :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object
Raymond Hettingerf7f64f92014-05-23 00:03:45 +0100520 more conveniently, use the ``is*()`` methods below.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
523.. attribute:: TarInfo.linkname
524
525 Name of the target file name, which is only present in :class:`TarInfo` objects
526 of type :const:`LNKTYPE` and :const:`SYMTYPE`.
527
528
529.. attribute:: TarInfo.uid
530
531 User ID of the user who originally stored this member.
532
533
534.. attribute:: TarInfo.gid
535
536 Group ID of the user who originally stored this member.
537
538
539.. attribute:: TarInfo.uname
540
541 User name.
542
543
544.. attribute:: TarInfo.gname
545
546 Group name.
547
548
549.. attribute:: TarInfo.pax_headers
550
551 A dictionary containing key-value pairs of an associated pax extended header.
552
Georg Brandl116aa622007-08-15 14:28:22 +0000553
554A :class:`TarInfo` object also provides some convenient query methods:
555
556
557.. method:: TarInfo.isfile()
558
559 Return :const:`True` if the :class:`Tarinfo` object is a regular file.
560
561
562.. method:: TarInfo.isreg()
563
564 Same as :meth:`isfile`.
565
566
567.. method:: TarInfo.isdir()
568
569 Return :const:`True` if it is a directory.
570
571
572.. method:: TarInfo.issym()
573
574 Return :const:`True` if it is a symbolic link.
575
576
577.. method:: TarInfo.islnk()
578
579 Return :const:`True` if it is a hard link.
580
581
582.. method:: TarInfo.ischr()
583
584 Return :const:`True` if it is a character device.
585
586
587.. method:: TarInfo.isblk()
588
589 Return :const:`True` if it is a block device.
590
591
592.. method:: TarInfo.isfifo()
593
594 Return :const:`True` if it is a FIFO.
595
596
597.. method:: TarInfo.isdev()
598
599 Return :const:`True` if it is one of character device, block device or FIFO.
600
Georg Brandl116aa622007-08-15 14:28:22 +0000601
Serhiy Storchakad27b4552013-11-24 01:53:29 +0200602.. _tarfile-commandline:
603
604Command Line Interface
605----------------------
606
607.. versionadded:: 3.4
608
609The :mod:`tarfile` module provides a simple command line interface to interact
610with tar archives.
611
612If you want to create a new tar archive, specify its name after the :option:`-c`
613option and then list the filename(s) that should be included::
614
615 $ python -m tarfile -c monty.tar spam.txt eggs.txt
616
617Passing a directory is also acceptable::
618
619 $ python -m tarfile -c monty.tar life-of-brian_1979/
620
621If you want to extract a tar archive into the current directory, use
622the :option:`-e` option::
623
624 $ python -m tarfile -e monty.tar
625
626You can also extract a tar archive into a different directory by passing the
627directory's name::
628
629 $ python -m tarfile -e monty.tar other-dir/
630
631For a list of the files in a tar archive, use the :option:`-l` option::
632
633 $ python -m tarfile -l monty.tar
634
635
636Command line options
637~~~~~~~~~~~~~~~~~~~~
638
639.. cmdoption:: -l <tarfile>
640 --list <tarfile>
641
642 List files in a tarfile.
643
644.. cmdoption:: -c <tarfile> <source1> <sourceN>
645 --create <tarfile> <source1> <sourceN>
646
647 Create tarfile from source files.
648
649.. cmdoption:: -e <tarfile> [<output_dir>]
650 --extract <tarfile> [<output_dir>]
651
652 Extract tarfile into the current directory if *output_dir* is not specified.
653
654.. cmdoption:: -t <tarfile>
655 --test <tarfile>
656
657 Test whether the tarfile is valid or not.
658
659.. cmdoption:: -v, --verbose
660
661 Verbose output
662
Georg Brandl116aa622007-08-15 14:28:22 +0000663.. _tar-examples:
664
665Examples
666--------
667
668How to extract an entire tar archive to the current working directory::
669
670 import tarfile
671 tar = tarfile.open("sample.tar.gz")
672 tar.extractall()
673 tar.close()
674
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000675How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
676a generator function instead of a list::
677
678 import os
679 import tarfile
680
681 def py_files(members):
682 for tarinfo in members:
683 if os.path.splitext(tarinfo.name)[1] == ".py":
684 yield tarinfo
685
686 tar = tarfile.open("sample.tar.gz")
687 tar.extractall(members=py_files(tar))
688 tar.close()
689
Georg Brandl116aa622007-08-15 14:28:22 +0000690How to create an uncompressed tar archive from a list of filenames::
691
692 import tarfile
693 tar = tarfile.open("sample.tar", "w")
694 for name in ["foo", "bar", "quux"]:
695 tar.add(name)
696 tar.close()
697
Lars Gustäbel01385812010-03-03 12:08:54 +0000698The same example using the :keyword:`with` statement::
699
700 import tarfile
701 with tarfile.open("sample.tar", "w") as tar:
702 for name in ["foo", "bar", "quux"]:
703 tar.add(name)
704
Georg Brandl116aa622007-08-15 14:28:22 +0000705How to read a gzip compressed tar archive and display some member information::
706
707 import tarfile
708 tar = tarfile.open("sample.tar.gz", "r:gz")
709 for tarinfo in tar:
Collin Winterc79461b2007-09-01 23:34:30 +0000710 print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000711 if tarinfo.isreg():
Collin Winterc79461b2007-09-01 23:34:30 +0000712 print("a regular file.")
Georg Brandl116aa622007-08-15 14:28:22 +0000713 elif tarinfo.isdir():
Collin Winterc79461b2007-09-01 23:34:30 +0000714 print("a directory.")
Georg Brandl116aa622007-08-15 14:28:22 +0000715 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000716 print("something else.")
Georg Brandl116aa622007-08-15 14:28:22 +0000717 tar.close()
718
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000719How to create an archive and reset the user information using the *filter*
720parameter in :meth:`TarFile.add`::
721
722 import tarfile
723 def reset(tarinfo):
724 tarinfo.uid = tarinfo.gid = 0
725 tarinfo.uname = tarinfo.gname = "root"
726 return tarinfo
727 tar = tarfile.open("sample.tar.gz", "w:gz")
728 tar.add("foo", filter=reset)
729 tar.close()
730
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732.. _tar-formats:
733
734Supported tar formats
735---------------------
736
737There are three tar formats that can be created with the :mod:`tarfile` module:
738
739* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
740 up to a length of at best 256 characters and linknames up to 100 characters. The
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200741 maximum file size is 8 GiB. This is an old and limited but widely
Georg Brandl116aa622007-08-15 14:28:22 +0000742 supported format.
743
744* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
Serhiy Storchakaf8def282013-02-16 17:29:56 +0200745 linknames, files bigger than 8 GiB and sparse files. It is the de facto
Georg Brandl116aa622007-08-15 14:28:22 +0000746 standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
747 extensions for long names, sparse file support is read-only.
748
749* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
750 format with virtually no limits. It supports long filenames and linknames, large
751 files and stores pathnames in a portable way. However, not all tar
752 implementations today are able to handle pax archives properly.
753
754 The *pax* format is an extension to the existing *ustar* format. It uses extra
755 headers for information that cannot be stored otherwise. There are two flavours
756 of pax headers: Extended headers only affect the subsequent file header, global
757 headers are valid for the complete archive and affect all following files. All
758 the data in a pax header is encoded in *UTF-8* for portability reasons.
759
760There are some more variants of the tar format which can be read, but not
761created:
762
763* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
764 storing only regular files and directories. Names must not be longer than 100
765 characters, there is no user/group name information. Some archives have
766 miscalculated header checksums in case of fields with non-ASCII characters.
767
768* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
769 pax format, but is not compatible.
770
Georg Brandl116aa622007-08-15 14:28:22 +0000771.. _tar-unicode:
772
773Unicode issues
774--------------
775
776The tar format was originally conceived to make backups on tape drives with the
777main focus on preserving file system information. Nowadays tar archives are
778commonly used for file distribution and exchanging archives over networks. One
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000779problem of the original format (which is the basis of all other formats) is
780that there is no concept of supporting different character encodings. For
Georg Brandl116aa622007-08-15 14:28:22 +0000781example, an ordinary tar archive created on a *UTF-8* system cannot be read
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000782correctly on a *Latin-1* system if it contains non-*ASCII* characters. Textual
783metadata (like filenames, linknames, user/group names) will appear damaged.
784Unfortunately, there is no way to autodetect the encoding of an archive. The
785pax format was designed to solve this problem. It stores non-ASCII metadata
786using the universal character encoding *UTF-8*.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000788The details of character conversion in :mod:`tarfile` are controlled by the
789*encoding* and *errors* keyword arguments of the :class:`TarFile` class.
Georg Brandl116aa622007-08-15 14:28:22 +0000790
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000791*encoding* defines the character encoding to use for the metadata in the
792archive. The default value is :func:`sys.getfilesystemencoding` or ``'ascii'``
793as a fallback. Depending on whether the archive is read or written, the
794metadata must be either decoded or encoded. If *encoding* is not set
795appropriately, this conversion may fail.
Georg Brandl116aa622007-08-15 14:28:22 +0000796
797The *errors* argument defines how characters are treated that cannot be
Victor Stinnerde629d42010-05-05 21:43:57 +0000798converted. Possible values are listed in section :ref:`codec-base-classes`.
799The default scheme is ``'surrogateescape'`` which Python also uses for its
800file system calls, see :ref:`os-filenames`.
Georg Brandl116aa622007-08-15 14:28:22 +0000801
Lars Gustäbel1465cc22010-05-17 18:02:50 +0000802In case of :const:`PAX_FORMAT` archives, *encoding* is generally not needed
803because all the metadata is stored using *UTF-8*. *encoding* is only used in
804the rare cases when binary pax headers are decoded or when strings with
805surrogate characters are stored.
806