blob: 60b9cd45f3a4ffcd2c22f4c3e443cbf8e0582132 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001.. _tarfile-mod:
2
3:mod:`tarfile` --- Read and write tar archive files
4===================================================
5
6.. module:: tarfile
7 :synopsis: Read and write tar-format archive files.
8
9
10.. versionadded:: 2.3
11
12.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
13.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
14
15
Mark Summerfieldaea6e592007-11-05 09:22:48 +000016The :mod:`tarfile` module makes it possible to read and write tar
17archives, including those using gzip or bz2 compression.
Georg Brandl2b92f6b2007-12-06 01:52:24 +000018(:file:`.zip` files can be read and written using the :mod:`zipfile` module.)
Mark Summerfieldaea6e592007-11-05 09:22:48 +000019
Georg Brandl8ec7f652007-08-15 14:28:01 +000020Some facts and figures:
21
Mark Summerfieldaea6e592007-11-05 09:22:48 +000022* reads and writes :mod:`gzip` and :mod:`bz2` compressed archives.
Georg Brandl8ec7f652007-08-15 14:28:01 +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*
27 extensions, read-only support for the *sparse* extension.
28
29* read/write support for the POSIX.1-2001 (pax) format.
30
31 .. versionadded:: 2.6
32
33* handles directories, regular files, hardlinks, symbolic links, fifos,
34 character devices and block devices and is able to acquire and restore file
35 information like timestamp, access permissions and owner.
36
Georg Brandl8ec7f652007-08-15 14:28:01 +000037
Lars Gustäbel4bfb5932008-05-17 16:50:22 +000038.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)
Georg Brandl8ec7f652007-08-15 14:28:01 +000039
40 Return a :class:`TarFile` object for the pathname *name*. For detailed
41 information on :class:`TarFile` objects and the keyword arguments that are
42 allowed, see :ref:`tarfile-objects`.
43
44 *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
45 to ``'r'``. Here is a full list of mode combinations:
46
47 +------------------+---------------------------------------------+
48 | mode | action |
49 +==================+=============================================+
50 | ``'r' or 'r:*'`` | Open for reading with transparent |
51 | | compression (recommended). |
52 +------------------+---------------------------------------------+
53 | ``'r:'`` | Open for reading exclusively without |
54 | | compression. |
55 +------------------+---------------------------------------------+
56 | ``'r:gz'`` | Open for reading with gzip compression. |
57 +------------------+---------------------------------------------+
58 | ``'r:bz2'`` | Open for reading with bzip2 compression. |
59 +------------------+---------------------------------------------+
60 | ``'a' or 'a:'`` | Open for appending with no compression. The |
61 | | file is created if it does not exist. |
62 +------------------+---------------------------------------------+
63 | ``'w' or 'w:'`` | Open for uncompressed writing. |
64 +------------------+---------------------------------------------+
65 | ``'w:gz'`` | Open for gzip compressed writing. |
66 +------------------+---------------------------------------------+
67 | ``'w:bz2'`` | Open for bzip2 compressed writing. |
68 +------------------+---------------------------------------------+
69
70 Note that ``'a:gz'`` or ``'a:bz2'`` is not possible. If *mode* is not suitable
71 to open a certain (compressed) file for reading, :exc:`ReadError` is raised. Use
72 *mode* ``'r'`` to avoid this. If a compression method is not supported,
73 :exc:`CompressionError` is raised.
74
75 If *fileobj* is specified, it is used as an alternative to a file object opened
76 for *name*. It is supposed to be at position 0.
77
78 For special purposes, there is a second format for *mode*:
Lars Gustäbel4bfb5932008-05-17 16:50:22 +000079 ``'filemode|[compression]'``. :func:`tarfile.open` will return a :class:`TarFile`
Georg Brandl8ec7f652007-08-15 14:28:01 +000080 object that processes its data as a stream of blocks. No random seeking will
81 be done on the file. If given, *fileobj* may be any object that has a
82 :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
83 specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
84 in combination with e.g. ``sys.stdin``, a socket file object or a tape
85 device. However, such a :class:`TarFile` object is limited in that it does
86 not allow to be accessed randomly, see :ref:`tar-examples`. The currently
87 possible modes:
88
89 +-------------+--------------------------------------------+
90 | Mode | Action |
91 +=============+============================================+
92 | ``'r|*'`` | Open a *stream* of tar blocks for reading |
93 | | with transparent compression. |
94 +-------------+--------------------------------------------+
95 | ``'r|'`` | Open a *stream* of uncompressed tar blocks |
96 | | for reading. |
97 +-------------+--------------------------------------------+
98 | ``'r|gz'`` | Open a gzip compressed *stream* for |
99 | | reading. |
100 +-------------+--------------------------------------------+
101 | ``'r|bz2'`` | Open a bzip2 compressed *stream* for |
102 | | reading. |
103 +-------------+--------------------------------------------+
104 | ``'w|'`` | Open an uncompressed *stream* for writing. |
105 +-------------+--------------------------------------------+
106 | ``'w|gz'`` | Open an gzip compressed *stream* for |
107 | | writing. |
108 +-------------+--------------------------------------------+
109 | ``'w|bz2'`` | Open an bzip2 compressed *stream* for |
110 | | writing. |
111 +-------------+--------------------------------------------+
112
113
114.. class:: TarFile
115
116 Class for reading and writing tar archives. Do not use this class directly,
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000117 better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118
119
120.. function:: is_tarfile(name)
121
122 Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
123 module can read.
124
125
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000126.. class:: TarFileCompat(filename, mode='r', compression=TAR_PLAIN)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128 Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
129 Please consult the documentation of the :mod:`zipfile` module for more details.
130 *compression* must be one of the following constants:
131
132
133 .. data:: TAR_PLAIN
134
135 Constant for an uncompressed tar archive.
136
137
138 .. data:: TAR_GZIPPED
139
140 Constant for a :mod:`gzip` compressed tar archive.
141
142
Lars Gustäbel727bd0b2008-08-02 11:26:39 +0000143 .. deprecated:: 2.6
144 The :class:`TarFileCompat` class has been deprecated for removal in Python 3.0.
145
146
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147.. exception:: TarError
148
149 Base class for all :mod:`tarfile` exceptions.
150
151
152.. exception:: ReadError
153
154 Is raised when a tar archive is opened, that either cannot be handled by the
155 :mod:`tarfile` module or is somehow invalid.
156
157
158.. exception:: CompressionError
159
160 Is raised when a compression method is not supported or when the data cannot be
161 decoded properly.
162
163
164.. exception:: StreamError
165
166 Is raised for the limitations that are typical for stream-like :class:`TarFile`
167 objects.
168
169
170.. exception:: ExtractError
171
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000172 Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173 :attr:`TarFile.errorlevel`\ ``== 2``.
174
175
176.. exception:: HeaderError
177
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000178 Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
180 .. versionadded:: 2.6
181
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000182
Georg Brandl8ec7f652007-08-15 14:28:01 +0000183Each 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
185details.
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
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000208The 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`.
215
216
Georg Brandl8ec7f652007-08-15 14:28:01 +0000217.. seealso::
218
219 Module :mod:`zipfile`
220 Documentation of the :mod:`zipfile` standard module.
221
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000222 `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +0000223 Documentation for tar archive files, including GNU tar extensions.
224
Georg Brandl8ec7f652007-08-15 14:28:01 +0000225
226.. _tarfile-objects:
227
228TarFile Objects
229---------------
230
231The :class:`TarFile` object provides an interface to a tar archive. A tar
232archive is a sequence of blocks. An archive member (a stored file) is made up of
233a header block followed by data blocks. It is possible to store a file in a tar
234archive several times. Each archive member is represented by a :class:`TarInfo`
235object, see :ref:`tarinfo-objects` for details.
236
Lars Gustäbel64581042010-03-03 11:55:48 +0000237A :class:`TarFile` object can be used as a context manager in a :keyword:`with`
238statement. It will automatically be closed when the block is completed. Please
239note that in the event of an exception an archive opened for writing will not
Andrew M. Kuchlingca2413e2010-04-11 01:40:06 +0000240be finalized; only the internally used file object will be closed. See the
Lars Gustäbel64581042010-03-03 11:55:48 +0000241:ref:`tar-examples` section for a use case.
242
243.. versionadded:: 2.7
244 Added support for the context manager protocol.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000245
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000246.. 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 Brandl8ec7f652007-08-15 14:28:01 +0000247
248 All following arguments are optional and can be accessed as instance attributes
249 as well.
250
251 *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
252 In this case, the file object's :attr:`name` attribute is used if it exists.
253
254 *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
255 data to an existing file or ``'w'`` to create a new file overwriting an existing
256 one.
257
258 If *fileobj* is given, it is used for reading or writing data. If it can be
259 determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
260 from position 0.
261
262 .. note::
263
264 *fileobj* is not closed, when :class:`TarFile` is closed.
265
266 *format* controls the archive format. It must be one of the constants
267 :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
268 defined at module level.
269
270 .. versionadded:: 2.6
271
272 The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
273 with a different one.
274
275 .. versionadded:: 2.6
276
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000277 If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
278 is :const:`True`, add the content of the target files to the archive. This has no
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279 effect on systems that do not support symbolic links.
280
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000281 If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
282 If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283 as possible. This is only useful for reading concatenated or damaged archives.
284
285 *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
286 messages). The messages are written to ``sys.stderr``.
287
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000288 If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000289 Nevertheless, they appear as error messages in the debug output, when debugging
290 is enabled. If ``1``, all *fatal* errors are raised as :exc:`OSError` or
291 :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
292 :exc:`TarError` exceptions as well.
293
294 The *encoding* and *errors* arguments control the way strings are converted to
295 unicode objects and vice versa. The default settings will work for most users.
296 See section :ref:`tar-unicode` for in-depth information.
297
298 .. versionadded:: 2.6
299
300 The *pax_headers* argument is an optional dictionary of unicode strings which
301 will be added as a pax global header if *format* is :const:`PAX_FORMAT`.
302
303 .. versionadded:: 2.6
304
305
306.. method:: TarFile.open(...)
307
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000308 Alternative constructor. The :func:`tarfile.open` function is actually a
309 shortcut to this classmethod.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000310
311
312.. method:: TarFile.getmember(name)
313
314 Return a :class:`TarInfo` object for member *name*. If *name* can not be found
315 in the archive, :exc:`KeyError` is raised.
316
317 .. note::
318
319 If a member occurs more than once in the archive, its last occurrence is assumed
320 to be the most up-to-date version.
321
322
323.. method:: TarFile.getmembers()
324
325 Return the members of the archive as a list of :class:`TarInfo` objects. The
326 list has the same order as the members in the archive.
327
328
329.. method:: TarFile.getnames()
330
331 Return the members as a list of their names. It has the same order as the list
332 returned by :meth:`getmembers`.
333
334
335.. method:: TarFile.list(verbose=True)
336
337 Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
338 only the names of the members are printed. If it is :const:`True`, output
339 similar to that of :program:`ls -l` is produced.
340
341
342.. method:: TarFile.next()
343
344 Return the next member of the archive as a :class:`TarInfo` object, when
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000345 :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
Georg Brandl8ec7f652007-08-15 14:28:01 +0000346 available.
347
348
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000349.. method:: TarFile.extractall(path=".", members=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000350
351 Extract all members from the archive to the current working directory or
352 directory *path*. If optional *members* is given, it must be a subset of the
353 list returned by :meth:`getmembers`. Directory information like owner,
354 modification time and permissions are set after all members have been extracted.
355 This is done to work around two problems: A directory's modification time is
356 reset each time a file is created in it. And, if a directory's permissions do
357 not allow writing, extracting files to it will fail.
358
Lars Gustäbel89241a32007-08-30 20:24:31 +0000359 .. warning::
360
361 Never extract archives from untrusted sources without prior inspection.
362 It is possible that files are created outside of *path*, e.g. members
363 that have absolute filenames starting with ``"/"`` or filenames with two
364 dots ``".."``.
365
Georg Brandl8ec7f652007-08-15 14:28:01 +0000366 .. versionadded:: 2.5
367
368
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000369.. method:: TarFile.extract(member, path="")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000370
371 Extract a member from the archive to the current working directory, using its
372 full name. Its file information is extracted as accurately as possible. *member*
373 may be a filename or a :class:`TarInfo` object. You can specify a different
374 directory using *path*.
375
376 .. note::
377
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000378 The :meth:`extract` method does not take care of several extraction issues.
379 In most cases you should consider using the :meth:`extractall` method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000380
Lars Gustäbel89241a32007-08-30 20:24:31 +0000381 .. warning::
382
383 See the warning for :meth:`extractall`.
384
Georg Brandl8ec7f652007-08-15 14:28:01 +0000385
386.. method:: TarFile.extractfile(member)
387
388 Extract a member from the archive as a file object. *member* may be a filename
389 or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
390 is returned. If *member* is a link, a file-like object is constructed from the
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000391 link's target. If *member* is none of the above, :const:`None` is returned.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000392
393 .. note::
394
Georg Brandlcf5608d2009-04-25 15:05:04 +0000395 The file-like object is read-only. It provides the methods
396 :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`,
397 and :meth:`close`, and also supports iteration over its lines.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000398
399
Lars Gustäbel21121e62009-09-12 10:28:15 +0000400.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, filter=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000401
402 Add the file *name* to the archive. *name* may be any type of file (directory,
403 fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
404 for the file in the archive. Directories are added recursively by default. This
405 can be avoided by setting *recursive* to :const:`False`. If *exclude* is given
406 it must be a function that takes one filename argument and returns a boolean
407 value. Depending on this value the respective file is either excluded
Lars Gustäbel21121e62009-09-12 10:28:15 +0000408 (:const:`True`) or added (:const:`False`). If *filter* is specified it must
409 be a function that takes a :class:`TarInfo` object argument and returns the
Andrew M. Kuchlingf5852f52009-10-05 21:24:35 +0000410 changed :class:`TarInfo` object. If it instead returns :const:`None` the :class:`TarInfo`
Lars Gustäbel21121e62009-09-12 10:28:15 +0000411 object will be excluded from the archive. See :ref:`tar-examples` for an
412 example.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000413
414 .. versionchanged:: 2.6
415 Added the *exclude* parameter.
416
Lars Gustäbel21121e62009-09-12 10:28:15 +0000417 .. versionchanged:: 2.7
418 Added the *filter* parameter.
419
420 .. deprecated:: 2.7
421 The *exclude* parameter is deprecated, please use the *filter* parameter
422 instead.
423
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000425.. method:: TarFile.addfile(tarinfo, fileobj=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426
427 Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
428 ``tarinfo.size`` bytes are read from it and added to the archive. You can
429 create :class:`TarInfo` objects using :meth:`gettarinfo`.
430
431 .. note::
432
433 On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
434 avoid irritation about the file size.
435
436
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000437.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438
439 Create a :class:`TarInfo` object for either the file *name* or the file object
440 *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify some
441 of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
442 If given, *arcname* specifies an alternative name for the file in the archive.
443
444
445.. method:: TarFile.close()
446
447 Close the :class:`TarFile`. In write mode, two finishing zero blocks are
448 appended to the archive.
449
450
451.. attribute:: TarFile.posix
452
453 Setting this to :const:`True` is equivalent to setting the :attr:`format`
454 attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to
455 :const:`GNU_FORMAT`.
456
457 .. versionchanged:: 2.4
458 *posix* defaults to :const:`False`.
459
460 .. deprecated:: 2.6
461 Use the :attr:`format` attribute instead.
462
463
464.. attribute:: TarFile.pax_headers
465
466 A dictionary containing key-value pairs of pax global headers.
467
468 .. versionadded:: 2.6
469
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470
471.. _tarinfo-objects:
472
473TarInfo Objects
474---------------
475
476A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
477from storing all required attributes of a file (like file type, size, time,
478permissions, owner etc.), it provides some useful methods to determine its type.
479It does *not* contain the file's data itself.
480
481:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
482:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
483
484
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000485.. class:: TarInfo(name="")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000486
487 Create a :class:`TarInfo` object.
488
489
490.. method:: TarInfo.frombuf(buf)
491
492 Create and return a :class:`TarInfo` object from string buffer *buf*.
493
494 .. versionadded:: 2.6
495 Raises :exc:`HeaderError` if the buffer is invalid..
496
497
498.. method:: TarInfo.fromtarfile(tarfile)
499
500 Read the next member from the :class:`TarFile` object *tarfile* and return it as
501 a :class:`TarInfo` object.
502
503 .. versionadded:: 2.6
504
505
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000506.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000507
508 Create a string buffer from a :class:`TarInfo` object. For information on the
509 arguments see the constructor of the :class:`TarFile` class.
510
511 .. versionchanged:: 2.6
512 The arguments were added.
513
514A ``TarInfo`` object has the following public data attributes:
515
516
517.. attribute:: TarInfo.name
518
519 Name of the archive member.
520
521
522.. attribute:: TarInfo.size
523
524 Size in bytes.
525
526
527.. attribute:: TarInfo.mtime
528
529 Time of last modification.
530
531
532.. attribute:: TarInfo.mode
533
534 Permission bits.
535
536
537.. attribute:: TarInfo.type
538
539 File type. *type* is usually one of these constants: :const:`REGTYPE`,
540 :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
541 :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
542 :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object
543 more conveniently, use the ``is_*()`` methods below.
544
545
546.. attribute:: TarInfo.linkname
547
548 Name of the target file name, which is only present in :class:`TarInfo` objects
549 of type :const:`LNKTYPE` and :const:`SYMTYPE`.
550
551
552.. attribute:: TarInfo.uid
553
554 User ID of the user who originally stored this member.
555
556
557.. attribute:: TarInfo.gid
558
559 Group ID of the user who originally stored this member.
560
561
562.. attribute:: TarInfo.uname
563
564 User name.
565
566
567.. attribute:: TarInfo.gname
568
569 Group name.
570
571
572.. attribute:: TarInfo.pax_headers
573
574 A dictionary containing key-value pairs of an associated pax extended header.
575
576 .. versionadded:: 2.6
577
578A :class:`TarInfo` object also provides some convenient query methods:
579
580
581.. method:: TarInfo.isfile()
582
583 Return :const:`True` if the :class:`Tarinfo` object is a regular file.
584
585
586.. method:: TarInfo.isreg()
587
588 Same as :meth:`isfile`.
589
590
591.. method:: TarInfo.isdir()
592
593 Return :const:`True` if it is a directory.
594
595
596.. method:: TarInfo.issym()
597
598 Return :const:`True` if it is a symbolic link.
599
600
601.. method:: TarInfo.islnk()
602
603 Return :const:`True` if it is a hard link.
604
605
606.. method:: TarInfo.ischr()
607
608 Return :const:`True` if it is a character device.
609
610
611.. method:: TarInfo.isblk()
612
613 Return :const:`True` if it is a block device.
614
615
616.. method:: TarInfo.isfifo()
617
618 Return :const:`True` if it is a FIFO.
619
620
621.. method:: TarInfo.isdev()
622
623 Return :const:`True` if it is one of character device, block device or FIFO.
624
Georg Brandl8ec7f652007-08-15 14:28:01 +0000625
626.. _tar-examples:
627
628Examples
629--------
630
631How to extract an entire tar archive to the current working directory::
632
633 import tarfile
634 tar = tarfile.open("sample.tar.gz")
635 tar.extractall()
636 tar.close()
637
Lars Gustäbel4bfb5932008-05-17 16:50:22 +0000638How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
639a generator function instead of a list::
640
641 import os
642 import tarfile
643
644 def py_files(members):
645 for tarinfo in members:
646 if os.path.splitext(tarinfo.name)[1] == ".py":
647 yield tarinfo
648
649 tar = tarfile.open("sample.tar.gz")
650 tar.extractall(members=py_files(tar))
651 tar.close()
652
Georg Brandl8ec7f652007-08-15 14:28:01 +0000653How to create an uncompressed tar archive from a list of filenames::
654
655 import tarfile
656 tar = tarfile.open("sample.tar", "w")
657 for name in ["foo", "bar", "quux"]:
658 tar.add(name)
659 tar.close()
660
Lars Gustäbel64581042010-03-03 11:55:48 +0000661The same example using the :keyword:`with` statement::
662
663 import tarfile
664 with tarfile.open("sample.tar", "w") as tar:
665 for name in ["foo", "bar", "quux"]:
666 tar.add(name)
667
Georg Brandl8ec7f652007-08-15 14:28:01 +0000668How to read a gzip compressed tar archive and display some member information::
669
670 import tarfile
671 tar = tarfile.open("sample.tar.gz", "r:gz")
672 for tarinfo in tar:
673 print tarinfo.name, "is", tarinfo.size, "bytes in size and is",
674 if tarinfo.isreg():
675 print "a regular file."
676 elif tarinfo.isdir():
677 print "a directory."
678 else:
679 print "something else."
680 tar.close()
681
Lars Gustäbel21121e62009-09-12 10:28:15 +0000682How to create an archive and reset the user information using the *filter*
683parameter in :meth:`TarFile.add`::
684
685 import tarfile
686 def reset(tarinfo):
687 tarinfo.uid = tarinfo.gid = 0
688 tarinfo.uname = tarinfo.gname = "root"
689 return tarinfo
690 tar = tarfile.open("sample.tar.gz", "w:gz")
691 tar.add("foo", filter=reset)
692 tar.close()
693
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
695.. _tar-formats:
696
697Supported tar formats
698---------------------
699
700There are three tar formats that can be created with the :mod:`tarfile` module:
701
702* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
703 up to a length of at best 256 characters and linknames up to 100 characters. The
704 maximum file size is 8 gigabytes. This is an old and limited but widely
705 supported format.
706
707* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
708 linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
709 standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
710 extensions for long names, sparse file support is read-only.
711
712* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
713 format with virtually no limits. It supports long filenames and linknames, large
714 files and stores pathnames in a portable way. However, not all tar
715 implementations today are able to handle pax archives properly.
716
717 The *pax* format is an extension to the existing *ustar* format. It uses extra
718 headers for information that cannot be stored otherwise. There are two flavours
719 of pax headers: Extended headers only affect the subsequent file header, global
720 headers are valid for the complete archive and affect all following files. All
721 the data in a pax header is encoded in *UTF-8* for portability reasons.
722
723There are some more variants of the tar format which can be read, but not
724created:
725
726* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
727 storing only regular files and directories. Names must not be longer than 100
728 characters, there is no user/group name information. Some archives have
729 miscalculated header checksums in case of fields with non-ASCII characters.
730
731* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
732 pax format, but is not compatible.
733
Georg Brandl8ec7f652007-08-15 14:28:01 +0000734.. _tar-unicode:
735
736Unicode issues
737--------------
738
739The tar format was originally conceived to make backups on tape drives with the
740main focus on preserving file system information. Nowadays tar archives are
741commonly used for file distribution and exchanging archives over networks. One
742problem of the original format (that all other formats are merely variants of)
743is that there is no concept of supporting different character encodings. For
744example, an ordinary tar archive created on a *UTF-8* system cannot be read
745correctly on a *Latin-1* system if it contains non-ASCII characters. Names (i.e.
746filenames, linknames, user/group names) containing these characters will appear
747damaged. Unfortunately, there is no way to autodetect the encoding of an
748archive.
749
750The pax format was designed to solve this problem. It stores non-ASCII names
751using the universal character encoding *UTF-8*. When a pax archive is read,
752these *UTF-8* names are converted to the encoding of the local file system.
753
754The details of unicode conversion are controlled by the *encoding* and *errors*
755keyword arguments of the :class:`TarFile` class.
756
757The default value for *encoding* is the local character encoding. It is deduced
758from :func:`sys.getfilesystemencoding` and :func:`sys.getdefaultencoding`. In
759read mode, *encoding* is used exclusively to convert unicode names from a pax
760archive to strings in the local character encoding. In write mode, the use of
761*encoding* depends on the chosen archive format. In case of :const:`PAX_FORMAT`,
762input names that contain non-ASCII characters need to be decoded before being
763stored as *UTF-8* strings. The other formats do not make use of *encoding*
764unless unicode objects are used as input names. These are converted to 8-bit
765character strings before they are added to the archive.
766
767The *errors* argument defines how characters are treated that cannot be
768converted to or from *encoding*. Possible values are listed in section
769:ref:`codec-base-classes`. In read mode, there is an additional scheme
770``'utf-8'`` which means that bad characters are replaced by their *UTF-8*
771representation. This is the default scheme. In write mode the default value for
772*errors* is ``'strict'`` to ensure that name information is not altered
773unnoticed.
774