blob: 9f049c11dd85bea248b9461d7a1b801cf3979023 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +000010.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
11.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
12
13
Guido van Rossum77677112007-11-05 19:43:04 +000014The :mod:`tarfile` module makes it possible to read and write tar
15archives, including those using gzip or bz2 compression.
Christian Heimes255f53b2007-12-08 15:33:56 +000016(:file:`.zip` files can be read and written using the :mod:`zipfile` module.)
Guido van Rossum77677112007-11-05 19:43:04 +000017
Georg Brandl116aa622007-08-15 14:28:22 +000018Some facts and figures:
19
Guido van Rossum77677112007-11-05 19:43:04 +000020* reads and writes :mod:`gzip` and :mod:`bz2` compressed archives.
Georg Brandl116aa622007-08-15 14:28:22 +000021
22* read/write support for the POSIX.1-1988 (ustar) format.
23
24* read/write support for the GNU tar format including *longname* and *longlink*
25 extensions, read-only support for the *sparse* extension.
26
27* read/write support for the POSIX.1-2001 (pax) format.
28
Georg Brandl116aa622007-08-15 14:28:22 +000029* handles directories, regular files, hardlinks, symbolic links, fifos,
30 character devices and block devices and is able to acquire and restore file
31 information like timestamp, access permissions and owner.
32
33* can handle tape devices.
34
35
36.. function:: open(name[, mode[, fileobj[, bufsize]]], **kwargs)
37
38 Return a :class:`TarFile` object for the pathname *name*. For detailed
39 information on :class:`TarFile` objects and the keyword arguments that are
40 allowed, see :ref:`tarfile-objects`.
41
42 *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
43 to ``'r'``. Here is a full list of mode combinations:
44
45 +------------------+---------------------------------------------+
46 | mode | action |
47 +==================+=============================================+
48 | ``'r' or 'r:*'`` | Open for reading with transparent |
49 | | compression (recommended). |
50 +------------------+---------------------------------------------+
51 | ``'r:'`` | Open for reading exclusively without |
52 | | compression. |
53 +------------------+---------------------------------------------+
54 | ``'r:gz'`` | Open for reading with gzip compression. |
55 +------------------+---------------------------------------------+
56 | ``'r:bz2'`` | Open for reading with bzip2 compression. |
57 +------------------+---------------------------------------------+
58 | ``'a' or 'a:'`` | Open for appending with no compression. The |
59 | | file is created if it does not exist. |
60 +------------------+---------------------------------------------+
61 | ``'w' or 'w:'`` | Open for uncompressed writing. |
62 +------------------+---------------------------------------------+
63 | ``'w:gz'`` | Open for gzip compressed writing. |
64 +------------------+---------------------------------------------+
65 | ``'w:bz2'`` | Open for bzip2 compressed writing. |
66 +------------------+---------------------------------------------+
67
68 Note that ``'a:gz'`` or ``'a:bz2'`` is not possible. If *mode* is not suitable
69 to open a certain (compressed) file for reading, :exc:`ReadError` is raised. Use
70 *mode* ``'r'`` to avoid this. If a compression method is not supported,
71 :exc:`CompressionError` is raised.
72
73 If *fileobj* is specified, it is used as an alternative to a file object opened
74 for *name*. It is supposed to be at position 0.
75
76 For special purposes, there is a second format for *mode*:
77 ``'filemode|[compression]'``. :func:`open` will return a :class:`TarFile`
78 object that processes its data as a stream of blocks. No random seeking will
79 be done on the file. If given, *fileobj* may be any object that has a
80 :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
81 specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
82 in combination with e.g. ``sys.stdin``, a socket file object or a tape
83 device. However, such a :class:`TarFile` object is limited in that it does
84 not allow to be accessed randomly, see :ref:`tar-examples`. The currently
85 possible modes:
86
87 +-------------+--------------------------------------------+
88 | Mode | Action |
89 +=============+============================================+
90 | ``'r|*'`` | Open a *stream* of tar blocks for reading |
91 | | with transparent compression. |
92 +-------------+--------------------------------------------+
93 | ``'r|'`` | Open a *stream* of uncompressed tar blocks |
94 | | for reading. |
95 +-------------+--------------------------------------------+
96 | ``'r|gz'`` | Open a gzip compressed *stream* for |
97 | | reading. |
98 +-------------+--------------------------------------------+
99 | ``'r|bz2'`` | Open a bzip2 compressed *stream* for |
100 | | reading. |
101 +-------------+--------------------------------------------+
102 | ``'w|'`` | Open an uncompressed *stream* for writing. |
103 +-------------+--------------------------------------------+
104 | ``'w|gz'`` | Open an gzip compressed *stream* for |
105 | | writing. |
106 +-------------+--------------------------------------------+
107 | ``'w|bz2'`` | Open an bzip2 compressed *stream* for |
108 | | writing. |
109 +-------------+--------------------------------------------+
110
111
112.. class:: TarFile
113
114 Class for reading and writing tar archives. Do not use this class directly,
115 better use :func:`open` instead. See :ref:`tarfile-objects`.
116
117
118.. function:: is_tarfile(name)
119
120 Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
121 module can read.
122
123
124.. class:: TarFileCompat(filename[, mode[, compression]])
125
126 Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
127 Please consult the documentation of the :mod:`zipfile` module for more details.
128 *compression* must be one of the following constants:
129
130
131 .. data:: TAR_PLAIN
132
133 Constant for an uncompressed tar archive.
134
135
136 .. data:: TAR_GZIPPED
137
138 Constant for a :mod:`gzip` compressed tar archive.
139
140
141.. exception:: TarError
142
143 Base class for all :mod:`tarfile` exceptions.
144
145
146.. exception:: ReadError
147
148 Is raised when a tar archive is opened, that either cannot be handled by the
149 :mod:`tarfile` module or is somehow invalid.
150
151
152.. exception:: CompressionError
153
154 Is raised when a compression method is not supported or when the data cannot be
155 decoded properly.
156
157
158.. exception:: StreamError
159
160 Is raised for the limitations that are typical for stream-like :class:`TarFile`
161 objects.
162
163
164.. exception:: ExtractError
165
166 Is raised for *non-fatal* errors when using :meth:`extract`, but only if
167 :attr:`TarFile.errorlevel`\ ``== 2``.
168
169
170.. exception:: HeaderError
171
172 Is raised by :meth:`frombuf` if the buffer it gets is invalid.
173
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175Each of the following constants defines a tar archive format that the
176:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
177details.
178
179
180.. data:: USTAR_FORMAT
181
182 POSIX.1-1988 (ustar) format.
183
184
185.. data:: GNU_FORMAT
186
187 GNU tar format.
188
189
190.. data:: PAX_FORMAT
191
192 POSIX.1-2001 (pax) format.
193
194
195.. data:: DEFAULT_FORMAT
196
197 The default format for creating archives. This is currently :const:`GNU_FORMAT`.
198
199
200.. seealso::
201
202 Module :mod:`zipfile`
203 Documentation of the :mod:`zipfile` standard module.
204
205 `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/tar_134.html#SEC134>`_
206 Documentation for tar archive files, including GNU tar extensions.
207
Georg Brandl116aa622007-08-15 14:28:22 +0000208
209.. _tarfile-objects:
210
211TarFile Objects
212---------------
213
214The :class:`TarFile` object provides an interface to a tar archive. A tar
215archive is a sequence of blocks. An archive member (a stored file) is made up of
216a header block followed by data blocks. It is possible to store a file in a tar
217archive several times. Each archive member is represented by a :class:`TarInfo`
218object, see :ref:`tarinfo-objects` for details.
219
220
221.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=None, errors=None, pax_headers=None, debug=0, errorlevel=0)
222
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
Georg Brandl116aa622007-08-15 14:28:22 +0000248 If *dereference* is ``False``, add symbolic and hard links to the archive. If it
249 is ``True``, add the content of the target files to the archive. This has no
250 effect on systems that do not support symbolic links.
251
252 If *ignore_zeros* is ``False``, treat an empty block as the end of the archive.
253 If it is *True*, skip empty (and invalid) blocks and try to get as many members
254 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
259 If *errorlevel* is ``0``, all errors are ignored when using :meth:`extract`.
260 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
276 Alternative constructor. The :func:`open` function on module level is actually a
277 shortcut to this classmethod. See section :ref:`tarfile-mod` for details.
278
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
313 :class:`TarFile` is opened for reading. Return ``None`` if there is no more
314 available.
315
316
317.. method:: TarFile.extractall([path[, members]])
318
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
335.. method:: TarFile.extract(member[, path])
336
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
344 Because the :meth:`extract` method allows random access to a tar archive there
345 are some issues you must take care of yourself. See the description for
346 :meth:`extractall` above.
347
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000348 .. warning::
349
350 See the warning for :meth:`extractall`.
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353.. method:: TarFile.extractfile(member)
354
355 Extract a member from the archive as a file object. *member* may be a filename
356 or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
357 is returned. If *member* is a link, a file-like object is constructed from the
358 link's target. If *member* is none of the above, ``None`` is returned.
359
360 .. note::
361
362 The file-like object is read-only and provides the following methods:
363 :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`.
364
365
366.. method:: TarFile.add(name[, arcname[, recursive[, exclude]]])
367
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
374 (:const:`True`) or added (:const:`False`).
375
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377.. method:: TarFile.addfile(tarinfo[, fileobj])
378
379 Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
380 ``tarinfo.size`` bytes are read from it and added to the archive. You can
381 create :class:`TarInfo` objects using :meth:`gettarinfo`.
382
383 .. note::
384
385 On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
386 avoid irritation about the file size.
387
388
389.. method:: TarFile.gettarinfo([name[, arcname[, fileobj]]])
390
391 Create a :class:`TarInfo` object for either the file *name* or the file object
392 *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify some
393 of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
394 If given, *arcname* specifies an alternative name for the file in the archive.
395
396
397.. method:: TarFile.close()
398
399 Close the :class:`TarFile`. In write mode, two finishing zero blocks are
400 appended to the archive.
401
402
403.. attribute:: TarFile.posix
404
405 Setting this to :const:`True` is equivalent to setting the :attr:`format`
406 attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to
407 :const:`GNU_FORMAT`.
408
Georg Brandl55ac8f02007-09-01 13:51:09 +0000409 *posix* defaults to :const:`False`.
Georg Brandl116aa622007-08-15 14:28:22 +0000410
411 .. deprecated:: 2.6
412 Use the :attr:`format` attribute instead.
413
414
415.. attribute:: TarFile.pax_headers
416
417 A dictionary containing key-value pairs of pax global headers.
418
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Georg Brandl116aa622007-08-15 14:28:22 +0000420
421.. _tarinfo-objects:
422
423TarInfo Objects
424---------------
425
426A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
427from storing all required attributes of a file (like file type, size, time,
428permissions, owner etc.), it provides some useful methods to determine its type.
429It does *not* contain the file's data itself.
430
431:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
432:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
433
434
435.. class:: TarInfo([name])
436
437 Create a :class:`TarInfo` object.
438
439
440.. method:: TarInfo.frombuf(buf)
441
442 Create and return a :class:`TarInfo` object from string buffer *buf*.
443
Georg Brandl55ac8f02007-09-01 13:51:09 +0000444 Raises :exc:`HeaderError` if the buffer is invalid..
Georg Brandl116aa622007-08-15 14:28:22 +0000445
446
447.. method:: TarInfo.fromtarfile(tarfile)
448
449 Read the next member from the :class:`TarFile` object *tarfile* and return it as
450 a :class:`TarInfo` object.
451
Georg Brandl116aa622007-08-15 14:28:22 +0000452
453.. method:: TarInfo.tobuf([format[, encoding [, errors]]])
454
455 Create a string buffer from a :class:`TarInfo` object. For information on the
456 arguments see the constructor of the :class:`TarFile` class.
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459A ``TarInfo`` object has the following public data attributes:
460
461
462.. attribute:: TarInfo.name
463
464 Name of the archive member.
465
466
467.. attribute:: TarInfo.size
468
469 Size in bytes.
470
471
472.. attribute:: TarInfo.mtime
473
474 Time of last modification.
475
476
477.. attribute:: TarInfo.mode
478
479 Permission bits.
480
481
482.. attribute:: TarInfo.type
483
484 File type. *type* is usually one of these constants: :const:`REGTYPE`,
485 :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
486 :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
487 :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object
488 more conveniently, use the ``is_*()`` methods below.
489
490
491.. attribute:: TarInfo.linkname
492
493 Name of the target file name, which is only present in :class:`TarInfo` objects
494 of type :const:`LNKTYPE` and :const:`SYMTYPE`.
495
496
497.. attribute:: TarInfo.uid
498
499 User ID of the user who originally stored this member.
500
501
502.. attribute:: TarInfo.gid
503
504 Group ID of the user who originally stored this member.
505
506
507.. attribute:: TarInfo.uname
508
509 User name.
510
511
512.. attribute:: TarInfo.gname
513
514 Group name.
515
516
517.. attribute:: TarInfo.pax_headers
518
519 A dictionary containing key-value pairs of an associated pax extended header.
520
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522A :class:`TarInfo` object also provides some convenient query methods:
523
524
525.. method:: TarInfo.isfile()
526
527 Return :const:`True` if the :class:`Tarinfo` object is a regular file.
528
529
530.. method:: TarInfo.isreg()
531
532 Same as :meth:`isfile`.
533
534
535.. method:: TarInfo.isdir()
536
537 Return :const:`True` if it is a directory.
538
539
540.. method:: TarInfo.issym()
541
542 Return :const:`True` if it is a symbolic link.
543
544
545.. method:: TarInfo.islnk()
546
547 Return :const:`True` if it is a hard link.
548
549
550.. method:: TarInfo.ischr()
551
552 Return :const:`True` if it is a character device.
553
554
555.. method:: TarInfo.isblk()
556
557 Return :const:`True` if it is a block device.
558
559
560.. method:: TarInfo.isfifo()
561
562 Return :const:`True` if it is a FIFO.
563
564
565.. method:: TarInfo.isdev()
566
567 Return :const:`True` if it is one of character device, block device or FIFO.
568
Georg Brandl116aa622007-08-15 14:28:22 +0000569
570.. _tar-examples:
571
572Examples
573--------
574
575How to extract an entire tar archive to the current working directory::
576
577 import tarfile
578 tar = tarfile.open("sample.tar.gz")
579 tar.extractall()
580 tar.close()
581
582How to create an uncompressed tar archive from a list of filenames::
583
584 import tarfile
585 tar = tarfile.open("sample.tar", "w")
586 for name in ["foo", "bar", "quux"]:
587 tar.add(name)
588 tar.close()
589
590How to read a gzip compressed tar archive and display some member information::
591
592 import tarfile
593 tar = tarfile.open("sample.tar.gz", "r:gz")
594 for tarinfo in tar:
Collin Winterc79461b2007-09-01 23:34:30 +0000595 print(tarinfo.name, "is", tarinfo.size, "bytes in size and is", end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000596 if tarinfo.isreg():
Collin Winterc79461b2007-09-01 23:34:30 +0000597 print("a regular file.")
Georg Brandl116aa622007-08-15 14:28:22 +0000598 elif tarinfo.isdir():
Collin Winterc79461b2007-09-01 23:34:30 +0000599 print("a directory.")
Georg Brandl116aa622007-08-15 14:28:22 +0000600 else:
Collin Winterc79461b2007-09-01 23:34:30 +0000601 print("something else.")
Georg Brandl116aa622007-08-15 14:28:22 +0000602 tar.close()
603
604How to create a tar archive with faked information::
605
606 import tarfile
607 tar = tarfile.open("sample.tar.gz", "w:gz")
608 for name in namelist:
609 tarinfo = tar.gettarinfo(name, "fakeproj-1.0/" + name)
610 tarinfo.uid = 123
611 tarinfo.gid = 456
612 tarinfo.uname = "johndoe"
613 tarinfo.gname = "fake"
614 tar.addfile(tarinfo, file(name))
615 tar.close()
616
617The *only* way to extract an uncompressed tar stream from ``sys.stdin``::
618
619 import sys
620 import tarfile
621 tar = tarfile.open(mode="r|", fileobj=sys.stdin)
622 for tarinfo in tar:
623 tar.extract(tarinfo)
624 tar.close()
625
Georg Brandl116aa622007-08-15 14:28:22 +0000626
627.. _tar-formats:
628
629Supported tar formats
630---------------------
631
632There are three tar formats that can be created with the :mod:`tarfile` module:
633
634* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
635 up to a length of at best 256 characters and linknames up to 100 characters. The
636 maximum file size is 8 gigabytes. This is an old and limited but widely
637 supported format.
638
639* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
640 linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
641 standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
642 extensions for long names, sparse file support is read-only.
643
644* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
645 format with virtually no limits. It supports long filenames and linknames, large
646 files and stores pathnames in a portable way. However, not all tar
647 implementations today are able to handle pax archives properly.
648
649 The *pax* format is an extension to the existing *ustar* format. It uses extra
650 headers for information that cannot be stored otherwise. There are two flavours
651 of pax headers: Extended headers only affect the subsequent file header, global
652 headers are valid for the complete archive and affect all following files. All
653 the data in a pax header is encoded in *UTF-8* for portability reasons.
654
655There are some more variants of the tar format which can be read, but not
656created:
657
658* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
659 storing only regular files and directories. Names must not be longer than 100
660 characters, there is no user/group name information. Some archives have
661 miscalculated header checksums in case of fields with non-ASCII characters.
662
663* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
664 pax format, but is not compatible.
665
Georg Brandl116aa622007-08-15 14:28:22 +0000666.. _tar-unicode:
667
668Unicode issues
669--------------
670
671The tar format was originally conceived to make backups on tape drives with the
672main focus on preserving file system information. Nowadays tar archives are
673commonly used for file distribution and exchanging archives over networks. One
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000674problem of the original format (which is the basis of all other formats) is
675that there is no concept of supporting different character encodings. For
Georg Brandl116aa622007-08-15 14:28:22 +0000676example, an ordinary tar archive created on a *UTF-8* system cannot be read
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000677correctly on a *Latin-1* system if it contains non-*ASCII* characters. Textual
678metadata (like filenames, linknames, user/group names) will appear damaged.
679Unfortunately, there is no way to autodetect the encoding of an archive. The
680pax format was designed to solve this problem. It stores non-ASCII metadata
681using the universal character encoding *UTF-8*.
Georg Brandl116aa622007-08-15 14:28:22 +0000682
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000683The details of character conversion in :mod:`tarfile` are controlled by the
684*encoding* and *errors* keyword arguments of the :class:`TarFile` class.
Georg Brandl116aa622007-08-15 14:28:22 +0000685
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000686*encoding* defines the character encoding to use for the metadata in the
687archive. The default value is :func:`sys.getfilesystemencoding` or ``'ascii'``
688as a fallback. Depending on whether the archive is read or written, the
689metadata must be either decoded or encoded. If *encoding* is not set
690appropriately, this conversion may fail.
Georg Brandl116aa622007-08-15 14:28:22 +0000691
692The *errors* argument defines how characters are treated that cannot be
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000693converted. Possible values are listed in section :ref:`codec-base-classes`. In
694read mode the default scheme is ``'replace'``. This avoids unexpected
695:exc:`UnicodeError` exceptions and guarantees that an archive can always be
696read. In write mode the default value for *errors* is ``'strict'``. This
697ensures that name information is not altered unnoticed.
Georg Brandl116aa622007-08-15 14:28:22 +0000698
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000699In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because
700non-ASCII metadata is stored using *UTF-8*.