blob: 85c067437e89885327de4d46431a389cfdc618bc [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
10.. versionadded:: 2.3
11
12.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
13.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>
14
15
16The :mod:`tarfile` module makes it possible to read and create tar archives.
17Some facts and figures:
18
19* reads and writes :mod:`gzip` and :mod:`bzip2` compressed archives.
20
21* read/write support for the POSIX.1-1988 (ustar) format.
22
23* read/write support for the GNU tar format including *longname* and *longlink*
24 extensions, read-only support for the *sparse* extension.
25
26* read/write support for the POSIX.1-2001 (pax) format.
27
28 .. versionadded:: 2.6
29
30* handles directories, regular files, hardlinks, symbolic links, fifos,
31 character devices and block devices and is able to acquire and restore file
32 information like timestamp, access permissions and owner.
33
34* can handle tape devices.
35
36
37.. function:: open(name[, mode[, fileobj[, bufsize]]], **kwargs)
38
39 Return a :class:`TarFile` object for the pathname *name*. For detailed
40 information on :class:`TarFile` objects and the keyword arguments that are
41 allowed, see :ref:`tarfile-objects`.
42
43 *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
44 to ``'r'``. Here is a full list of mode combinations:
45
46 +------------------+---------------------------------------------+
47 | mode | action |
48 +==================+=============================================+
49 | ``'r' or 'r:*'`` | Open for reading with transparent |
50 | | compression (recommended). |
51 +------------------+---------------------------------------------+
52 | ``'r:'`` | Open for reading exclusively without |
53 | | compression. |
54 +------------------+---------------------------------------------+
55 | ``'r:gz'`` | Open for reading with gzip compression. |
56 +------------------+---------------------------------------------+
57 | ``'r:bz2'`` | Open for reading with bzip2 compression. |
58 +------------------+---------------------------------------------+
59 | ``'a' or 'a:'`` | Open for appending with no compression. The |
60 | | file is created if it does not exist. |
61 +------------------+---------------------------------------------+
62 | ``'w' or 'w:'`` | Open for uncompressed writing. |
63 +------------------+---------------------------------------------+
64 | ``'w:gz'`` | Open for gzip compressed writing. |
65 +------------------+---------------------------------------------+
66 | ``'w:bz2'`` | Open for bzip2 compressed writing. |
67 +------------------+---------------------------------------------+
68
69 Note that ``'a:gz'`` or ``'a:bz2'`` is not possible. If *mode* is not suitable
70 to open a certain (compressed) file for reading, :exc:`ReadError` is raised. Use
71 *mode* ``'r'`` to avoid this. If a compression method is not supported,
72 :exc:`CompressionError` is raised.
73
74 If *fileobj* is specified, it is used as an alternative to a file object opened
75 for *name*. It is supposed to be at position 0.
76
77 For special purposes, there is a second format for *mode*:
78 ``'filemode|[compression]'``. :func:`open` will return a :class:`TarFile`
79 object that processes its data as a stream of blocks. No random seeking will
80 be done on the file. If given, *fileobj* may be any object that has a
81 :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
82 specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
83 in combination with e.g. ``sys.stdin``, a socket file object or a tape
84 device. However, such a :class:`TarFile` object is limited in that it does
85 not allow to be accessed randomly, see :ref:`tar-examples`. The currently
86 possible modes:
87
88 +-------------+--------------------------------------------+
89 | Mode | Action |
90 +=============+============================================+
91 | ``'r|*'`` | Open a *stream* of tar blocks for reading |
92 | | with transparent compression. |
93 +-------------+--------------------------------------------+
94 | ``'r|'`` | Open a *stream* of uncompressed tar blocks |
95 | | for reading. |
96 +-------------+--------------------------------------------+
97 | ``'r|gz'`` | Open a gzip compressed *stream* for |
98 | | reading. |
99 +-------------+--------------------------------------------+
100 | ``'r|bz2'`` | Open a bzip2 compressed *stream* for |
101 | | reading. |
102 +-------------+--------------------------------------------+
103 | ``'w|'`` | Open an uncompressed *stream* for writing. |
104 +-------------+--------------------------------------------+
105 | ``'w|gz'`` | Open an gzip compressed *stream* for |
106 | | writing. |
107 +-------------+--------------------------------------------+
108 | ``'w|bz2'`` | Open an bzip2 compressed *stream* for |
109 | | writing. |
110 +-------------+--------------------------------------------+
111
112
113.. class:: TarFile
114
115 Class for reading and writing tar archives. Do not use this class directly,
116 better use :func:`open` instead. See :ref:`tarfile-objects`.
117
118
119.. function:: is_tarfile(name)
120
121 Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
122 module can read.
123
124
125.. class:: TarFileCompat(filename[, mode[, compression]])
126
127 Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
128 Please consult the documentation of the :mod:`zipfile` module for more details.
129 *compression* must be one of the following constants:
130
131
132 .. data:: TAR_PLAIN
133
134 Constant for an uncompressed tar archive.
135
136
137 .. data:: TAR_GZIPPED
138
139 Constant for a :mod:`gzip` compressed tar archive.
140
141
142.. exception:: TarError
143
144 Base class for all :mod:`tarfile` exceptions.
145
146
147.. exception:: ReadError
148
149 Is raised when a tar archive is opened, that either cannot be handled by the
150 :mod:`tarfile` module or is somehow invalid.
151
152
153.. exception:: CompressionError
154
155 Is raised when a compression method is not supported or when the data cannot be
156 decoded properly.
157
158
159.. exception:: StreamError
160
161 Is raised for the limitations that are typical for stream-like :class:`TarFile`
162 objects.
163
164
165.. exception:: ExtractError
166
167 Is raised for *non-fatal* errors when using :meth:`extract`, but only if
168 :attr:`TarFile.errorlevel`\ ``== 2``.
169
170
171.. exception:: HeaderError
172
173 Is raised by :meth:`frombuf` if the buffer it gets is invalid.
174
175 .. versionadded:: 2.6
176
177Each of the following constants defines a tar archive format that the
178:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
179details.
180
181
182.. data:: USTAR_FORMAT
183
184 POSIX.1-1988 (ustar) format.
185
186
187.. data:: GNU_FORMAT
188
189 GNU tar format.
190
191
192.. data:: PAX_FORMAT
193
194 POSIX.1-2001 (pax) format.
195
196
197.. data:: DEFAULT_FORMAT
198
199 The default format for creating archives. This is currently :const:`GNU_FORMAT`.
200
201
202.. seealso::
203
204 Module :mod:`zipfile`
205 Documentation of the :mod:`zipfile` standard module.
206
207 `GNU tar manual, Basic Tar Format <http://www.gnu.org/software/tar/manual/html_node/tar_134.html#SEC134>`_
208 Documentation for tar archive files, including GNU tar extensions.
209
210.. % -----------------
211.. % TarFile Objects
212.. % -----------------
213
214
215.. _tarfile-objects:
216
217TarFile Objects
218---------------
219
220The :class:`TarFile` object provides an interface to a tar archive. A tar
221archive is a sequence of blocks. An archive member (a stored file) is made up of
222a header block followed by data blocks. It is possible to store a file in a tar
223archive several times. Each archive member is represented by a :class:`TarInfo`
224object, see :ref:`tarinfo-objects` for details.
225
226
227.. 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)
228
229 All following arguments are optional and can be accessed as instance attributes
230 as well.
231
232 *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
233 In this case, the file object's :attr:`name` attribute is used if it exists.
234
235 *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
236 data to an existing file or ``'w'`` to create a new file overwriting an existing
237 one.
238
239 If *fileobj* is given, it is used for reading or writing data. If it can be
240 determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
241 from position 0.
242
243 .. note::
244
245 *fileobj* is not closed, when :class:`TarFile` is closed.
246
247 *format* controls the archive format. It must be one of the constants
248 :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
249 defined at module level.
250
251 .. versionadded:: 2.6
252
253 The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
254 with a different one.
255
256 .. versionadded:: 2.6
257
258 If *dereference* is ``False``, add symbolic and hard links to the archive. If it
259 is ``True``, add the content of the target files to the archive. This has no
260 effect on systems that do not support symbolic links.
261
262 If *ignore_zeros* is ``False``, treat an empty block as the end of the archive.
263 If it is *True*, skip empty (and invalid) blocks and try to get as many members
264 as possible. This is only useful for reading concatenated or damaged archives.
265
266 *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
267 messages). The messages are written to ``sys.stderr``.
268
269 If *errorlevel* is ``0``, all errors are ignored when using :meth:`extract`.
270 Nevertheless, they appear as error messages in the debug output, when debugging
271 is enabled. If ``1``, all *fatal* errors are raised as :exc:`OSError` or
272 :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
273 :exc:`TarError` exceptions as well.
274
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000275 The *encoding* and *errors* arguments define the character encoding to be
276 used for reading or writing the archive and how conversion errors are going
277 to be handled. The default settings will work for most users.
Georg Brandl116aa622007-08-15 14:28:22 +0000278 See section :ref:`tar-unicode` for in-depth information.
279
280 .. versionadded:: 2.6
281
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000282 The *pax_headers* argument is an optional dictionary of strings which
Georg Brandl116aa622007-08-15 14:28:22 +0000283 will be added as a pax global header if *format* is :const:`PAX_FORMAT`.
284
285 .. versionadded:: 2.6
286
287
288.. method:: TarFile.open(...)
289
290 Alternative constructor. The :func:`open` function on module level is actually a
291 shortcut to this classmethod. See section :ref:`tarfile-mod` for details.
292
293
294.. method:: TarFile.getmember(name)
295
296 Return a :class:`TarInfo` object for member *name*. If *name* can not be found
297 in the archive, :exc:`KeyError` is raised.
298
299 .. note::
300
301 If a member occurs more than once in the archive, its last occurrence is assumed
302 to be the most up-to-date version.
303
304
305.. method:: TarFile.getmembers()
306
307 Return the members of the archive as a list of :class:`TarInfo` objects. The
308 list has the same order as the members in the archive.
309
310
311.. method:: TarFile.getnames()
312
313 Return the members as a list of their names. It has the same order as the list
314 returned by :meth:`getmembers`.
315
316
317.. method:: TarFile.list(verbose=True)
318
319 Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
320 only the names of the members are printed. If it is :const:`True`, output
321 similar to that of :program:`ls -l` is produced.
322
323
324.. method:: TarFile.next()
325
326 Return the next member of the archive as a :class:`TarInfo` object, when
327 :class:`TarFile` is opened for reading. Return ``None`` if there is no more
328 available.
329
330
331.. method:: TarFile.extractall([path[, members]])
332
333 Extract all members from the archive to the current working directory or
334 directory *path*. If optional *members* is given, it must be a subset of the
335 list returned by :meth:`getmembers`. Directory information like owner,
336 modification time and permissions are set after all members have been extracted.
337 This is done to work around two problems: A directory's modification time is
338 reset each time a file is created in it. And, if a directory's permissions do
339 not allow writing, extracting files to it will fail.
340
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000341 .. warning::
342
343 Never extract archives from untrusted sources without prior inspection.
344 It is possible that files are created outside of *path*, e.g. members
345 that have absolute filenames starting with ``"/"`` or filenames with two
346 dots ``".."``.
347
Georg Brandl116aa622007-08-15 14:28:22 +0000348 .. versionadded:: 2.5
349
350
351.. method:: TarFile.extract(member[, path])
352
353 Extract a member from the archive to the current working directory, using its
354 full name. Its file information is extracted as accurately as possible. *member*
355 may be a filename or a :class:`TarInfo` object. You can specify a different
356 directory using *path*.
357
358 .. note::
359
360 Because the :meth:`extract` method allows random access to a tar archive there
361 are some issues you must take care of yourself. See the description for
362 :meth:`extractall` above.
363
Thomas Wouters47b49bf2007-08-30 22:15:33 +0000364 .. warning::
365
366 See the warning for :meth:`extractall`.
367
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369.. method:: TarFile.extractfile(member)
370
371 Extract a member from the archive as a file object. *member* may be a filename
372 or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
373 is returned. If *member* is a link, a file-like object is constructed from the
374 link's target. If *member* is none of the above, ``None`` is returned.
375
376 .. note::
377
378 The file-like object is read-only and provides the following methods:
379 :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`.
380
381
382.. method:: TarFile.add(name[, arcname[, recursive[, exclude]]])
383
384 Add the file *name* to the archive. *name* may be any type of file (directory,
385 fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
386 for the file in the archive. Directories are added recursively by default. This
387 can be avoided by setting *recursive* to :const:`False`. If *exclude* is given
388 it must be a function that takes one filename argument and returns a boolean
389 value. Depending on this value the respective file is either excluded
390 (:const:`True`) or added (:const:`False`).
391
392 .. versionchanged:: 2.6
393 Added the *exclude* parameter.
394
395
396.. method:: TarFile.addfile(tarinfo[, fileobj])
397
398 Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
399 ``tarinfo.size`` bytes are read from it and added to the archive. You can
400 create :class:`TarInfo` objects using :meth:`gettarinfo`.
401
402 .. note::
403
404 On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
405 avoid irritation about the file size.
406
407
408.. method:: TarFile.gettarinfo([name[, arcname[, fileobj]]])
409
410 Create a :class:`TarInfo` object for either the file *name* or the file object
411 *fileobj* (using :func:`os.fstat` on its file descriptor). You can modify some
412 of the :class:`TarInfo`'s attributes before you add it using :meth:`addfile`.
413 If given, *arcname* specifies an alternative name for the file in the archive.
414
415
416.. method:: TarFile.close()
417
418 Close the :class:`TarFile`. In write mode, two finishing zero blocks are
419 appended to the archive.
420
421
422.. attribute:: TarFile.posix
423
424 Setting this to :const:`True` is equivalent to setting the :attr:`format`
425 attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to
426 :const:`GNU_FORMAT`.
427
428 .. versionchanged:: 2.4
429 *posix* defaults to :const:`False`.
430
431 .. deprecated:: 2.6
432 Use the :attr:`format` attribute instead.
433
434
435.. attribute:: TarFile.pax_headers
436
437 A dictionary containing key-value pairs of pax global headers.
438
439 .. versionadded:: 2.6
440
441.. % -----------------
442.. % TarInfo Objects
443.. % -----------------
444
445
446.. _tarinfo-objects:
447
448TarInfo Objects
449---------------
450
451A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
452from storing all required attributes of a file (like file type, size, time,
453permissions, owner etc.), it provides some useful methods to determine its type.
454It does *not* contain the file's data itself.
455
456:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
457:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.
458
459
460.. class:: TarInfo([name])
461
462 Create a :class:`TarInfo` object.
463
464
465.. method:: TarInfo.frombuf(buf)
466
467 Create and return a :class:`TarInfo` object from string buffer *buf*.
468
469 .. versionadded:: 2.6
470 Raises :exc:`HeaderError` if the buffer is invalid..
471
472
473.. method:: TarInfo.fromtarfile(tarfile)
474
475 Read the next member from the :class:`TarFile` object *tarfile* and return it as
476 a :class:`TarInfo` object.
477
478 .. versionadded:: 2.6
479
480
481.. method:: TarInfo.tobuf([format[, encoding [, errors]]])
482
483 Create a string buffer from a :class:`TarInfo` object. For information on the
484 arguments see the constructor of the :class:`TarFile` class.
485
486 .. versionchanged:: 2.6
487 The arguments were added.
488
489A ``TarInfo`` object has the following public data attributes:
490
491
492.. attribute:: TarInfo.name
493
494 Name of the archive member.
495
496
497.. attribute:: TarInfo.size
498
499 Size in bytes.
500
501
502.. attribute:: TarInfo.mtime
503
504 Time of last modification.
505
506
507.. attribute:: TarInfo.mode
508
509 Permission bits.
510
511
512.. attribute:: TarInfo.type
513
514 File type. *type* is usually one of these constants: :const:`REGTYPE`,
515 :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
516 :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
517 :const:`GNUTYPE_SPARSE`. To determine the type of a :class:`TarInfo` object
518 more conveniently, use the ``is_*()`` methods below.
519
520
521.. attribute:: TarInfo.linkname
522
523 Name of the target file name, which is only present in :class:`TarInfo` objects
524 of type :const:`LNKTYPE` and :const:`SYMTYPE`.
525
526
527.. attribute:: TarInfo.uid
528
529 User ID of the user who originally stored this member.
530
531
532.. attribute:: TarInfo.gid
533
534 Group ID of the user who originally stored this member.
535
536
537.. attribute:: TarInfo.uname
538
539 User name.
540
541
542.. attribute:: TarInfo.gname
543
544 Group name.
545
546
547.. attribute:: TarInfo.pax_headers
548
549 A dictionary containing key-value pairs of an associated pax extended header.
550
551 .. versionadded:: 2.6
552
553A :class:`TarInfo` object also provides some convenient query methods:
554
555
556.. method:: TarInfo.isfile()
557
558 Return :const:`True` if the :class:`Tarinfo` object is a regular file.
559
560
561.. method:: TarInfo.isreg()
562
563 Same as :meth:`isfile`.
564
565
566.. method:: TarInfo.isdir()
567
568 Return :const:`True` if it is a directory.
569
570
571.. method:: TarInfo.issym()
572
573 Return :const:`True` if it is a symbolic link.
574
575
576.. method:: TarInfo.islnk()
577
578 Return :const:`True` if it is a hard link.
579
580
581.. method:: TarInfo.ischr()
582
583 Return :const:`True` if it is a character device.
584
585
586.. method:: TarInfo.isblk()
587
588 Return :const:`True` if it is a block device.
589
590
591.. method:: TarInfo.isfifo()
592
593 Return :const:`True` if it is a FIFO.
594
595
596.. method:: TarInfo.isdev()
597
598 Return :const:`True` if it is one of character device, block device or FIFO.
599
600.. % ------------------------
601.. % Examples
602.. % ------------------------
603
604
605.. _tar-examples:
606
607Examples
608--------
609
610How to extract an entire tar archive to the current working directory::
611
612 import tarfile
613 tar = tarfile.open("sample.tar.gz")
614 tar.extractall()
615 tar.close()
616
617How to create an uncompressed tar archive from a list of filenames::
618
619 import tarfile
620 tar = tarfile.open("sample.tar", "w")
621 for name in ["foo", "bar", "quux"]:
622 tar.add(name)
623 tar.close()
624
625How to read a gzip compressed tar archive and display some member information::
626
627 import tarfile
628 tar = tarfile.open("sample.tar.gz", "r:gz")
629 for tarinfo in tar:
630 print tarinfo.name, "is", tarinfo.size, "bytes in size and is",
631 if tarinfo.isreg():
632 print "a regular file."
633 elif tarinfo.isdir():
634 print "a directory."
635 else:
636 print "something else."
637 tar.close()
638
639How to create a tar archive with faked information::
640
641 import tarfile
642 tar = tarfile.open("sample.tar.gz", "w:gz")
643 for name in namelist:
644 tarinfo = tar.gettarinfo(name, "fakeproj-1.0/" + name)
645 tarinfo.uid = 123
646 tarinfo.gid = 456
647 tarinfo.uname = "johndoe"
648 tarinfo.gname = "fake"
649 tar.addfile(tarinfo, file(name))
650 tar.close()
651
652The *only* way to extract an uncompressed tar stream from ``sys.stdin``::
653
654 import sys
655 import tarfile
656 tar = tarfile.open(mode="r|", fileobj=sys.stdin)
657 for tarinfo in tar:
658 tar.extract(tarinfo)
659 tar.close()
660
661.. % ------------
662.. % Tar format
663.. % ------------
664
665
666.. _tar-formats:
667
668Supported tar formats
669---------------------
670
671There are three tar formats that can be created with the :mod:`tarfile` module:
672
673* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
674 up to a length of at best 256 characters and linknames up to 100 characters. The
675 maximum file size is 8 gigabytes. This is an old and limited but widely
676 supported format.
677
678* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
679 linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
680 standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
681 extensions for long names, sparse file support is read-only.
682
683* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
684 format with virtually no limits. It supports long filenames and linknames, large
685 files and stores pathnames in a portable way. However, not all tar
686 implementations today are able to handle pax archives properly.
687
688 The *pax* format is an extension to the existing *ustar* format. It uses extra
689 headers for information that cannot be stored otherwise. There are two flavours
690 of pax headers: Extended headers only affect the subsequent file header, global
691 headers are valid for the complete archive and affect all following files. All
692 the data in a pax header is encoded in *UTF-8* for portability reasons.
693
694There are some more variants of the tar format which can be read, but not
695created:
696
697* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
698 storing only regular files and directories. Names must not be longer than 100
699 characters, there is no user/group name information. Some archives have
700 miscalculated header checksums in case of fields with non-ASCII characters.
701
702* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
703 pax format, but is not compatible.
704
705.. % ----------------
706.. % Unicode issues
707.. % ----------------
708
709
710.. _tar-unicode:
711
712Unicode issues
713--------------
714
715The tar format was originally conceived to make backups on tape drives with the
716main focus on preserving file system information. Nowadays tar archives are
717commonly used for file distribution and exchanging archives over networks. One
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000718problem of the original format (which is the basis of all other formats) is
719that there is no concept of supporting different character encodings. For
Georg Brandl116aa622007-08-15 14:28:22 +0000720example, an ordinary tar archive created on a *UTF-8* system cannot be read
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000721correctly on a *Latin-1* system if it contains non-*ASCII* characters. Textual
722metadata (like filenames, linknames, user/group names) will appear damaged.
723Unfortunately, there is no way to autodetect the encoding of an archive. The
724pax format was designed to solve this problem. It stores non-ASCII metadata
725using the universal character encoding *UTF-8*.
Georg Brandl116aa622007-08-15 14:28:22 +0000726
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000727The details of character conversion in :mod:`tarfile` are controlled by the
728*encoding* and *errors* keyword arguments of the :class:`TarFile` class.
Georg Brandl116aa622007-08-15 14:28:22 +0000729
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000730*encoding* defines the character encoding to use for the metadata in the
731archive. The default value is :func:`sys.getfilesystemencoding` or ``'ascii'``
732as a fallback. Depending on whether the archive is read or written, the
733metadata must be either decoded or encoded. If *encoding* is not set
734appropriately, this conversion may fail.
Georg Brandl116aa622007-08-15 14:28:22 +0000735
736The *errors* argument defines how characters are treated that cannot be
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000737converted. Possible values are listed in section :ref:`codec-base-classes`. In
738read mode the default scheme is ``'replace'``. This avoids unexpected
739:exc:`UnicodeError` exceptions and guarantees that an archive can always be
740read. In write mode the default value for *errors* is ``'strict'``. This
741ensures that name information is not altered unnoticed.
Georg Brandl116aa622007-08-15 14:28:22 +0000742
Lars Gustäbel3741eff2007-08-21 12:17:05 +0000743In case of writing :const:`PAX_FORMAT` archives, *encoding* is ignored because
744non-ASCII metadata is stored using *UTF-8*.