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