blob: 8b53b578247a061d858140e9240308d748982f3e [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
11
Guido van Rossum77677112007-11-05 19:43:04 +000012The :mod:`tarfile` module makes it possible to read and write tar
13archives, including those using gzip or bz2 compression.
Christian Heimes255f53b2007-12-08 15:33:56 +000014(:file:`.zip` files can be read and written using the :mod:`zipfile` module.)
Guido van Rossum77677112007-11-05 19:43:04 +000015
Georg Brandl116aa622007-08-15 14:28:22 +000016Some facts and figures:
17
Guido van Rossum77677112007-11-05 19:43:04 +000018* reads and writes :mod:`gzip` and :mod:`bz2` compressed archives.
Georg Brandl116aa622007-08-15 14:28:22 +000019
20* read/write support for the POSIX.1-1988 (ustar) format.
21
22* read/write support for the GNU tar format including *longname* and *longlink*
23 extensions, read-only support for the *sparse* extension.
24
25* read/write support for the POSIX.1-2001 (pax) format.
26
Georg Brandl116aa622007-08-15 14:28:22 +000027* handles directories, regular files, hardlinks, symbolic links, fifos,
28 character devices and block devices and is able to acquire and restore file
29 information like timestamp, access permissions and owner.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031
Benjamin Petersona37cfc62008-05-26 13:48:34 +000032.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
Georg Brandl116aa622007-08-15 14:28:22 +000033
34 Return a :class:`TarFile` object for the pathname *name*. For detailed
35 information on :class:`TarFile` objects and the keyword arguments that are
36 allowed, see :ref:`tarfile-objects`.
37
38 *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
39 to ``'r'``. Here is a full list of mode combinations:
40
41 +------------------+---------------------------------------------+
42 | mode | action |
43 +==================+=============================================+
44 | ``'r' or 'r:*'`` | Open for reading with transparent |
45 | | compression (recommended). |
46 +------------------+---------------------------------------------+
47 | ``'r:'`` | Open for reading exclusively without |
48 | | compression. |
49 +------------------+---------------------------------------------+
50 | ``'r:gz'`` | Open for reading with gzip compression. |
51 +------------------+---------------------------------------------+
52 | ``'r:bz2'`` | Open for reading with bzip2 compression. |
53 +------------------+---------------------------------------------+
54 | ``'a' or 'a:'`` | Open for appending with no compression. The |
55 | | file is created if it does not exist. |
56 +------------------+---------------------------------------------+
57 | ``'w' or 'w:'`` | Open for uncompressed writing. |
58 +------------------+---------------------------------------------+
59 | ``'w:gz'`` | Open for gzip compressed writing. |
60 +------------------+---------------------------------------------+
61 | ``'w:bz2'`` | Open for bzip2 compressed writing. |
62 +------------------+---------------------------------------------+
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
70 for *name*. It is supposed to be at position 0.
71
72 For special purposes, there is a second format for *mode*:
Benjamin Petersona37cfc62008-05-26 13:48:34 +000073 ``'filemode|[compression]'``. :func:`tarfile.open` will return a :class:`TarFile`
Georg Brandl116aa622007-08-15 14:28:22 +000074 object that processes its data as a stream of blocks. No random seeking will
75 be done on the file. If given, *fileobj* may be any object that has a
76 :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
77 specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
78 in combination with e.g. ``sys.stdin``, a socket file object or a tape
79 device. However, such a :class:`TarFile` object is limited in that it does
80 not allow to be accessed randomly, see :ref:`tar-examples`. The currently
81 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 |
90 | | for reading. |
91 +-------------+--------------------------------------------+
92 | ``'r|gz'`` | Open a gzip compressed *stream* for |
93 | | reading. |
94 +-------------+--------------------------------------------+
95 | ``'r|bz2'`` | Open a bzip2 compressed *stream* for |
96 | | reading. |
97 +-------------+--------------------------------------------+
98 | ``'w|'`` | Open an uncompressed *stream* for writing. |
99 +-------------+--------------------------------------------+
100 | ``'w|gz'`` | Open an gzip compressed *stream* for |
101 | | writing. |
102 +-------------+--------------------------------------------+
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,
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000111 better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
Georg Brandl116aa622007-08-15 14:28:22 +0000112
113
114.. function:: is_tarfile(name)
115
116 Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
117 module can read.
118
119
Lars Gustäbel0c24e8b2008-08-02 11:43:24 +0000120The :mod:`tarfile` module defines the following exceptions:
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122
123.. exception:: TarError
124
125 Base class for all :mod:`tarfile` exceptions.
126
127
128.. exception:: ReadError
129
130 Is raised when a tar archive is opened, that either cannot be handled by the
131 :mod:`tarfile` module or is somehow invalid.
132
133
134.. exception:: CompressionError
135
136 Is raised when a compression method is not supported or when the data cannot be
137 decoded properly.
138
139
140.. exception:: StreamError
141
142 Is raised for the limitations that are typical for stream-like :class:`TarFile`
143 objects.
144
145
146.. exception:: ExtractError
147
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000148 Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
Georg Brandl116aa622007-08-15 14:28:22 +0000149 :attr:`TarFile.errorlevel`\ ``== 2``.
150
151
152.. exception:: HeaderError
153
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000154 Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.
155
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158Each of the following constants defines a tar archive format that the
159:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
160details.
161
162
163.. data:: USTAR_FORMAT
164
165 POSIX.1-1988 (ustar) format.
166
167
168.. data:: GNU_FORMAT
169
170 GNU tar format.
171
172
173.. data:: PAX_FORMAT
174
175 POSIX.1-2001 (pax) format.
176
177
178.. data:: DEFAULT_FORMAT
179
180 The default format for creating archives. This is currently :const:`GNU_FORMAT`.
181
182
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000183The following variables are available on module level:
184
185
186.. data:: ENCODING
187
188 The default character encoding i.e. the value from either
189 :func:`sys.getfilesystemencoding` or :func:`sys.getdefaultencoding`.
190
191
Georg Brandl116aa622007-08-15 14:28:22 +0000192.. seealso::
193
194 Module :mod:`zipfile`
195 Documentation of the :mod:`zipfile` standard module.
196
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000197 `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000198 Documentation for tar archive files, including GNU tar extensions.
199
Georg Brandl116aa622007-08-15 14:28:22 +0000200
201.. _tarfile-objects:
202
203TarFile Objects
204---------------
205
206The :class:`TarFile` object provides an interface to a tar archive. A tar
207archive is a sequence of blocks. An archive member (a stored file) is made up of
208a header block followed by data blocks. It is possible to store a file in a tar
209archive several times. Each archive member is represented by a :class:`TarInfo`
210object, see :ref:`tarinfo-objects` for details.
211
Lars Gustäbel01385812010-03-03 12:08:54 +0000212A :class:`TarFile` object can be used as a context manager in a :keyword:`with`
213statement. It will automatically be closed when the block is completed. Please
214note that in the event of an exception an archive opened for writing will not
215be finalized, only the internally used file object will be closed. See the
216:ref:`tar-examples` section for a use case.
217
218.. versionadded:: 3.2
219 Added support for the context manager protocol.
Georg Brandl116aa622007-08-15 14:28:22 +0000220
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000221.. 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)
Georg Brandl116aa622007-08-15 14:28:22 +0000222
223 All following arguments are optional and can be accessed as instance attributes
224 as well.
225
226 *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
227 In this case, the file object's :attr:`name` attribute is used if it exists.
228
229 *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
230 data to an existing file or ``'w'`` to create a new file overwriting an existing
231 one.
232
233 If *fileobj* is given, it is used for reading or writing data. If it can be
234 determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
235 from position 0.
236
237 .. note::
238
239 *fileobj* is not closed, when :class:`TarFile` is closed.
240
241 *format* controls the archive format. It must be one of the constants
242 :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
243 defined at module level.
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245 The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
246 with a different one.
247
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000248 If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
249 is :const:`True`, add the content of the target files to the archive. This has no
Georg Brandl116aa622007-08-15 14:28:22 +0000250 effect on systems that do not support symbolic links.
251
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000252 If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
253 If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
Georg Brandl116aa622007-08-15 14:28:22 +0000254 as possible. This is only useful for reading concatenated or damaged archives.
255
256 *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
257 messages). The messages are written to ``sys.stderr``.
258
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000259 If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
Georg Brandl116aa622007-08-15 14:28:22 +0000260 Nevertheless, they appear as error messages in the debug output, when debugging
261 is enabled. If ``1``, all *fatal* errors are raised as :exc:`OSError` or
262 :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
263 :exc:`TarError` exceptions as well.
264
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000265 The *encoding* and *errors* arguments define the character encoding to be
266 used for reading or writing the archive and how conversion errors are going
267 to be handled. The default settings will work for most users.
Georg Brandl116aa622007-08-15 14:28:22 +0000268 See section :ref:`tar-unicode` for in-depth information.
269
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000270 The *pax_headers* argument is an optional dictionary of strings which
Georg Brandl116aa622007-08-15 14:28:22 +0000271 will be added as a pax global header if *format* is :const:`PAX_FORMAT`.
272
Georg Brandl116aa622007-08-15 14:28:22 +0000273
274.. method:: TarFile.open(...)
275
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000276 Alternative constructor. The :func:`tarfile.open` function is actually a
277 shortcut to this classmethod.
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279
280.. method:: TarFile.getmember(name)
281
282 Return a :class:`TarInfo` object for member *name*. If *name* can not be found
283 in the archive, :exc:`KeyError` is raised.
284
285 .. note::
286
287 If a member occurs more than once in the archive, its last occurrence is assumed
288 to be the most up-to-date version.
289
290
291.. method:: TarFile.getmembers()
292
293 Return the members of the archive as a list of :class:`TarInfo` objects. The
294 list has the same order as the members in the archive.
295
296
297.. method:: TarFile.getnames()
298
299 Return the members as a list of their names. It has the same order as the list
300 returned by :meth:`getmembers`.
301
302
303.. method:: TarFile.list(verbose=True)
304
305 Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
306 only the names of the members are printed. If it is :const:`True`, output
307 similar to that of :program:`ls -l` is produced.
308
309
310.. method:: TarFile.next()
311
312 Return the next member of the archive as a :class:`TarInfo` object, when
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000313 :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
Georg Brandl116aa622007-08-15 14:28:22 +0000314 available.
315
316
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000317.. method:: TarFile.extractall(path=".", members=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319 Extract all members from the archive to the current working directory or
320 directory *path*. If optional *members* is given, it must be a subset of the
321 list returned by :meth:`getmembers`. Directory information like owner,
322 modification time and permissions are set after all members have been extracted.
323 This is done to work around two problems: A directory's modification time is
324 reset each time a file is created in it. And, if a directory's permissions do
325 not allow writing, extracting files to it will fail.
326
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000327 .. warning::
328
329 Never extract archives from untrusted sources without prior inspection.
330 It is possible that files are created outside of *path*, e.g. members
331 that have absolute filenames starting with ``"/"`` or filenames with two
332 dots ``".."``.
333
Georg Brandl116aa622007-08-15 14:28:22 +0000334
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000335.. method:: TarFile.extract(member, path="")
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 Extract a member from the archive to the current working directory, using its
338 full name. Its file information is extracted as accurately as possible. *member*
339 may be a filename or a :class:`TarInfo` object. You can specify a different
340 directory using *path*.
341
342 .. note::
343
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000344 The :meth:`extract` method does not take care of several extraction issues.
345 In most cases you should consider using the :meth:`extractall` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000347 .. warning::
348
349 See the warning for :meth:`extractall`.
350
Georg Brandl116aa622007-08-15 14:28:22 +0000351
352.. method:: TarFile.extractfile(member)
353
354 Extract a member from the archive as a file object. *member* may be a filename
355 or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
356 is returned. If *member* is a link, a file-like object is constructed from the
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000357 link's target. If *member* is none of the above, :const:`None` is returned.
Georg Brandl116aa622007-08-15 14:28:22 +0000358
359 .. note::
360
Georg Brandlff2ad0e2009-04-27 16:51:45 +0000361 The file-like object is read-only. It provides the methods
362 :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`,
363 and :meth:`close`, and also supports iteration over its lines.
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000366.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, filter=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368 Add the file *name* to the archive. *name* may be any type of file (directory,
369 fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
370 for the file in the archive. Directories are added recursively by default. This
Georg Brandl55ac8f02007-09-01 13:51:09 +0000371 can be avoided by setting *recursive* to :const:`False`. If *exclude* is given,
Georg Brandl116aa622007-08-15 14:28:22 +0000372 it must be a function that takes one filename argument and returns a boolean
373 value. Depending on this value the respective file is either excluded
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000374 (:const:`True`) or added (:const:`False`). If *filter* is specified it must
375 be a function that takes a :class:`TarInfo` object argument and returns the
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000376 changed :class:`TarInfo` object. If it instead returns :const:`None` the :class:`TarInfo`
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000377 object will be excluded from the archive. See :ref:`tar-examples` for an
378 example.
379
380 .. versionchanged:: 3.2
381 Added the *filter* parameter.
382
383 .. deprecated:: 3.2
384 The *exclude* parameter is deprecated, please use the *filter* parameter
385 instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
Georg Brandl116aa622007-08-15 14:28:22 +0000387
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000388.. method:: TarFile.addfile(tarinfo, fileobj=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390 Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
391 ``tarinfo.size`` bytes are read from it and added to the archive. You can
392 create :class:`TarInfo` objects using :meth:`gettarinfo`.
393
394 .. note::
395
396 On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
397 avoid irritation about the file size.
398
399
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000400.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000401
402 Create a :class:`TarInfo` object for either the file *name* or the file object
403 *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify some
404 of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
405 If given, *arcname* specifies an alternative name for the file in the archive.
406
407
408.. method:: TarFile.close()
409
410 Close the :class:`TarFile`. In write mode, two finishing zero blocks are
411 appended to the archive.
412
413
Georg Brandl116aa622007-08-15 14:28:22 +0000414.. attribute:: TarFile.pax_headers
415
416 A dictionary containing key-value pairs of pax global headers.
417
Georg Brandl116aa622007-08-15 14:28:22 +0000418
Georg Brandl116aa622007-08-15 14:28:22 +0000419
420.. _tarinfo-objects:
421
422TarInfo Objects
423---------------
424
425A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
426from storing all required attributes of a file (like file type, size, time,
427permissions, owner etc.), it provides some useful methods to determine its type.
428It does *not* contain the file's data itself.
429
430:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
431:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
432
433
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000434.. class:: TarInfo(name="")
Georg Brandl116aa622007-08-15 14:28:22 +0000435
436 Create a :class:`TarInfo` object.
437
438
439.. method:: TarInfo.frombuf(buf)
440
441 Create and return a :class:`TarInfo` object from string buffer *buf*.
442
Georg Brandl55ac8f02007-09-01 13:51:09 +0000443 Raises :exc:`HeaderError` if the buffer is invalid..
Georg Brandl116aa622007-08-15 14:28:22 +0000444
445
446.. method:: TarInfo.fromtarfile(tarfile)
447
448 Read the next member from the :class:`TarFile` object *tarfile* and return it as
449 a :class:`TarInfo` object.
450
Georg Brandl116aa622007-08-15 14:28:22 +0000451
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000452.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict')
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454 Create a string buffer from a :class:`TarInfo` object. For information on the
455 arguments see the constructor of the :class:`TarFile` class.
456
Georg Brandl116aa622007-08-15 14:28:22 +0000457
458A ``TarInfo`` object has the following public data attributes:
459
460
461.. attribute:: TarInfo.name
462
463 Name of the archive member.
464
465
466.. attribute:: TarInfo.size
467
468 Size in bytes.
469
470
471.. attribute:: TarInfo.mtime
472
473 Time of last modification.
474
475
476.. attribute:: TarInfo.mode
477
478 Permission bits.
479
480
481.. attribute:: TarInfo.type
482
483 File type. *type* is usually one of these constants: :const:`REGTYPE`,
484 :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
485 :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
486 :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object
487 more conveniently, use the ``is_*()`` methods below.
488
489
490.. attribute:: TarInfo.linkname
491
492 Name of the target file name, which is only present in :class:`TarInfo` objects
493 of type :const:`LNKTYPE` and :const:`SYMTYPE`.
494
495
496.. attribute:: TarInfo.uid
497
498 User ID of the user who originally stored this member.
499
500
501.. attribute:: TarInfo.gid
502
503 Group ID of the user who originally stored this member.
504
505
506.. attribute:: TarInfo.uname
507
508 User name.
509
510
511.. attribute:: TarInfo.gname
512
513 Group name.
514
515
516.. attribute:: TarInfo.pax_headers
517
518 A dictionary containing key-value pairs of an associated pax extended header.
519
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521A :class:`TarInfo` object also provides some convenient query methods:
522
523
524.. method:: TarInfo.isfile()
525
526 Return :const:`True` if the :class:`Tarinfo` object is a regular file.
527
528
529.. method:: TarInfo.isreg()
530
531 Same as :meth:`isfile`.
532
533
534.. method:: TarInfo.isdir()
535
536 Return :const:`True` if it is a directory.
537
538
539.. method:: TarInfo.issym()
540
541 Return :const:`True` if it is a symbolic link.
542
543
544.. method:: TarInfo.islnk()
545
546 Return :const:`True` if it is a hard link.
547
548
549.. method:: TarInfo.ischr()
550
551 Return :const:`True` if it is a character device.
552
553
554.. method:: TarInfo.isblk()
555
556 Return :const:`True` if it is a block device.
557
558
559.. method:: TarInfo.isfifo()
560
561 Return :const:`True` if it is a FIFO.
562
563
564.. method:: TarInfo.isdev()
565
566 Return :const:`True` if it is one of character device, block device or FIFO.
567
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569.. _tar-examples:
570
571Examples
572--------
573
574How to extract an entire tar archive to the current working directory::
575
576 import tarfile
577 tar = tarfile.open("sample.tar.gz")
578 tar.extractall()
579 tar.close()
580
Benjamin Petersona37cfc62008-05-26 13:48:34 +0000581How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
582a generator function instead of a list::
583
584 import os
585 import tarfile
586
587 def py_files(members):
588 for tarinfo in members:
589 if os.path.splitext(tarinfo.name)[1] == ".py":
590 yield tarinfo
591
592 tar = tarfile.open("sample.tar.gz")
593 tar.extractall(members=py_files(tar))
594 tar.close()
595
Georg Brandl116aa622007-08-15 14:28:22 +0000596How to create an uncompressed tar archive from a list of filenames::
597
598 import tarfile
599 tar = tarfile.open("sample.tar", "w")
600 for name in ["foo", "bar", "quux"]:
601 tar.add(name)
602 tar.close()
603
Lars Gustäbel01385812010-03-03 12:08:54 +0000604The same example using the :keyword:`with` statement::
605
606 import tarfile
607 with tarfile.open("sample.tar", "w") as tar:
608 for name in ["foo", "bar", "quux"]:
609 tar.add(name)
610
Georg Brandl116aa622007-08-15 14:28:22 +0000611How to read a gzip compressed tar archive and display some member information::
612
613 import tarfile
614 tar = tarfile.open("sample.tar.gz", "r:gz")
615 for tarinfo in tar:
Collin Winterc79461b2007-09-01 23:34:30 +0000616 print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000617 if tarinfo.isreg():
Collin Winterc79461b2007-09-01 23:34:30 +0000618 print("a regular file.")
Georg Brandl116aa622007-08-15 14:28:22 +0000619 elif tarinfo.isdir():
Collin Winterc79461b2007-09-01 23:34:30 +0000620 print("a directory.")
Georg Brandl116aa622007-08-15 14:28:22 +0000621 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000622 print("something else.")
Georg Brandl116aa622007-08-15 14:28:22 +0000623 tar.close()
624
Lars Gustäbel049d2aa2009-09-12 10:44:00 +0000625How to create an archive and reset the user information using the *filter*
626parameter in :meth:`TarFile.add`::
627
628 import tarfile
629 def reset(tarinfo):
630 tarinfo.uid = tarinfo.gid = 0
631 tarinfo.uname = tarinfo.gname = "root"
632 return tarinfo
633 tar = tarfile.open("sample.tar.gz", "w:gz")
634 tar.add("foo", filter=reset)
635 tar.close()
636
Georg Brandl116aa622007-08-15 14:28:22 +0000637
638.. _tar-formats:
639
640Supported tar formats
641---------------------
642
643There are three tar formats that can be created with the :mod:`tarfile` module:
644
645* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
646 up to a length of at best 256 characters and linknames up to 100 characters. The
647 maximum file size is 8 gigabytes. This is an old and limited but widely
648 supported format.
649
650* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
651 linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
652 standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
653 extensions for long names, sparse file support is read-only.
654
655* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
656 format with virtually no limits. It supports long filenames and linknames, large
657 files and stores pathnames in a portable way. However, not all tar
658 implementations today are able to handle pax archives properly.
659
660 The *pax* format is an extension to the existing *ustar* format. It uses extra
661 headers for information that cannot be stored otherwise. There are two flavours
662 of pax headers: Extended headers only affect the subsequent file header, global
663 headers are valid for the complete archive and affect all following files. All
664 the data in a pax header is encoded in *UTF-8* for portability reasons.
665
666There are some more variants of the tar format which can be read, but not
667created:
668
669* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
670 storing only regular files and directories. Names must not be longer than 100
671 characters, there is no user/group name information. Some archives have
672 miscalculated header checksums in case of fields with non-ASCII characters.
673
674* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
675 pax format, but is not compatible.
676
Georg Brandl116aa622007-08-15 14:28:22 +0000677.. _tar-unicode:
678
679Unicode issues
680--------------
681
682The tar format was originally conceived to make backups on tape drives with the
683main focus on preserving file system information. Nowadays tar archives are
684commonly used for file distribution and exchanging archives over networks. One
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000685problem of the original format (which is the basis of all other formats) is
686that there is no concept of supporting different character encodings. For
Georg Brandl116aa622007-08-15 14:28:22 +0000687example, an ordinary tar archive created on a *UTF-8* system cannot be read
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000688correctly on a *Latin-1* system if it contains non-*ASCII* characters. Textual
689metadata (like filenames, linknames, user/group names) will appear damaged.
690Unfortunately, there is no way to autodetect the encoding of an archive. The
691pax format was designed to solve this problem. It stores non-ASCII metadata
692using the universal character encoding *UTF-8*.
Georg Brandl116aa622007-08-15 14:28:22 +0000693
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000694The details of character conversion in :mod:`tarfile` are controlled by the
695*encoding* and *errors* keyword arguments of the :class:`TarFile` class.
Georg Brandl116aa622007-08-15 14:28:22 +0000696
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000697*encoding* defines the character encoding to use for the metadata in the
698archive. The default value is :func:`sys.getfilesystemencoding` or ``'ascii'``
699as a fallback. Depending on whether the archive is read or written, the
700metadata must be either decoded or encoded. If *encoding* is not set
701appropriately, this conversion may fail.
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703The *errors* argument defines how characters are treated that cannot be
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000704converted. Possible values are listed in section :ref:`codec-base-classes`. In
705read mode the default scheme is ``'replace'``. This avoids unexpected
706:exc:`UnicodeError` exceptions and guarantees that an archive can always be
707read. In write mode the default value for *errors* is ``'strict'``. This
708ensures that name information is not altered unnoticed.
Georg Brandl116aa622007-08-15 14:28:22 +0000709
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000710In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because
711non-ASCII metadata is stored using *UTF-8*.