blob: 30a03614ba53873ed7090e9d8bbd9f94f7d2a061 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`zipfile` --- Work with ZIP archives
2=========================================
3
4.. module:: zipfile
5 :synopsis: Read and write ZIP-format archive files.
6.. moduleauthor:: James C. Ahlstrom <jim@interet.com>
7.. sectionauthor:: James C. Ahlstrom <jim@interet.com>
8
Georg Brandl8ec7f652007-08-15 14:28:01 +00009.. versionadded:: 1.6
10
Éric Araujo29a0b572011-08-19 02:14:03 +020011**Source code:** :source:`Lib/zipfile.py`
12
13--------------
14
Georg Brandl8ec7f652007-08-15 14:28:01 +000015The ZIP file format is a common archive and compression standard. This module
16provides tools to create, read, write, append, and list a ZIP file. Any
17advanced use of this module will require an understanding of the format, as
18defined in `PKZIP Application Note
Georg Brandl02677812008-03-15 00:20:19 +000019<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
Georg Brandl8ec7f652007-08-15 14:28:01 +000020
Georg Brandl7d4bfb32010-08-02 21:44:25 +000021This module does not currently handle multi-disk ZIP files.
22It can handle ZIP files that use the ZIP64 extensions
Mark Summerfield91f94292007-11-05 14:38:50 +000023(that is ZIP files that are more than 4 GByte in size). It supports
24decryption of encrypted files in ZIP archives, but it currently cannot
Gregory P. Smithda407232008-01-20 01:32:00 +000025create an encrypted file. Decryption is extremely slow as it is
Georg Brandl8c18a472009-11-18 19:39:14 +000026implemented in native Python rather than C.
Georg Brandl8ec7f652007-08-15 14:28:01 +000027
Mark Summerfieldaea6e592007-11-05 09:22:48 +000028For other archive formats, see the :mod:`bz2`, :mod:`gzip`, and
29:mod:`tarfile` modules.
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
Mark Summerfieldaea6e592007-11-05 09:22:48 +000031The module defines the following items:
Georg Brandl8ec7f652007-08-15 14:28:01 +000032
33.. exception:: BadZipfile
34
35 The error raised for bad ZIP files (old name: ``zipfile.error``).
36
37
38.. exception:: LargeZipFile
39
40 The error raised when a ZIP file would require ZIP64 functionality but that has
41 not been enabled.
42
43
44.. class:: ZipFile
Georg Brandl3b85b9b2010-11-26 08:20:18 +000045 :noindex:
Georg Brandl8ec7f652007-08-15 14:28:01 +000046
47 The class for reading and writing ZIP files. See section
48 :ref:`zipfile-objects` for constructor details.
49
50
51.. class:: PyZipFile
52
53 Class for creating ZIP archives containing Python libraries.
54
55
56.. class:: ZipInfo([filename[, date_time]])
57
58 Class used to represent information about a member of an archive. Instances
59 of this class are returned by the :meth:`getinfo` and :meth:`infolist`
60 methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
61 will not need to create these, but only use those created by this
62 module. *filename* should be the full name of the archive member, and
63 *date_time* should be a tuple containing six fields which describe the time
64 of the last modification to the file; the fields are described in section
65 :ref:`zipinfo-objects`.
66
67
68.. function:: is_zipfile(filename)
69
70 Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
Antoine Pitrou6f193e02008-12-27 15:43:12 +000071 otherwise returns ``False``. *filename* may be a file or file-like object too.
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
Antoine Pitrou6f193e02008-12-27 15:43:12 +000073 .. versionchanged:: 2.7
Benjamin Petersonfbaeca72008-12-27 22:18:58 +000074 Support for file and file-like objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +000075
76.. data:: ZIP_STORED
77
78 The numeric constant for an uncompressed archive member.
79
80
81.. data:: ZIP_DEFLATED
82
83 The numeric constant for the usual ZIP compression method. This requires the
84 zlib module. No other compression methods are currently supported.
85
86
87.. seealso::
88
Georg Brandl02677812008-03-15 00:20:19 +000089 `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
Georg Brandl8ec7f652007-08-15 14:28:01 +000090 Documentation on the ZIP file format by Phil Katz, the creator of the format and
91 algorithms used.
92
93 `Info-ZIP Home Page <http://www.info-zip.org/>`_
94 Information about the Info-ZIP project's ZIP archive programs and development
95 libraries.
96
97
98.. _zipfile-objects:
99
100ZipFile Objects
101---------------
102
103
104.. class:: ZipFile(file[, mode[, compression[, allowZip64]]])
105
106 Open a ZIP file, where *file* can be either a path to a file (a string) or a
107 file-like object. The *mode* parameter should be ``'r'`` to read an existing
108 file, ``'w'`` to truncate and write a new file, or ``'a'`` to append to an
Ezio Melotti569e61f2009-12-30 06:14:51 +0000109 existing file. If *mode* is ``'a'`` and *file* refers to an existing ZIP
110 file, then additional files are added to it. If *file* does not refer to a
111 ZIP file, then a new ZIP archive is appended to the file. This is meant for
112 adding a ZIP archive to another file (such as :file:`python.exe`).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000113
114 .. versionchanged:: 2.6
Ezio Melotti569e61f2009-12-30 06:14:51 +0000115 If *mode* is ``a`` and the file does not exist at all, it is created.
116
117 *compression* is the ZIP compression method to use when writing the archive,
118 and should be :const:`ZIP_STORED` or :const:`ZIP_DEFLATED`; unrecognized
119 values will cause :exc:`RuntimeError` to be raised. If :const:`ZIP_DEFLATED`
120 is specified but the :mod:`zlib` module is not available, :exc:`RuntimeError`
121 is also raised. The default is :const:`ZIP_STORED`. If *allowZip64* is
122 ``True`` zipfile will create ZIP files that use the ZIP64 extensions when
123 the zipfile is larger than 2 GB. If it is false (the default) :mod:`zipfile`
124 will raise an exception when the ZIP file would require ZIP64 extensions.
125 ZIP64 extensions are disabled by default because the default :program:`zip`
126 and :program:`unzip` commands on Unix (the InfoZIP utilities) don't support
127 these extensions.
128
Georg Brandlda29acd2010-12-21 17:58:06 +0000129 .. versionchanged:: 2.7.1
130 If the file is created with mode ``'a'`` or ``'w'`` and then
131 :meth:`close`\ d without adding any files to the archive, the appropriate
132 ZIP structures for an empty archive will be written to the file.
Georg Brandl86e0c892010-11-26 07:22:28 +0000133
Ezio Melotti569e61f2009-12-30 06:14:51 +0000134 ZipFile is also a context manager and therefore supports the
135 :keyword:`with` statement. In the example, *myzip* is closed after the
136 :keyword:`with` statement's suite is finished---even if an exception occurs::
137
138 with ZipFile('spam.zip', 'w') as myzip:
139 myzip.write('eggs.txt')
140
141 .. versionadded:: 2.7
142 Added the ability to use :class:`ZipFile` as a context manager.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000143
144
145.. method:: ZipFile.close()
146
147 Close the archive file. You must call :meth:`close` before exiting your program
148 or essential records will not be written.
149
150
151.. method:: ZipFile.getinfo(name)
152
153 Return a :class:`ZipInfo` object with information about the archive member
154 *name*. Calling :meth:`getinfo` for a name not currently contained in the
155 archive will raise a :exc:`KeyError`.
156
157
158.. method:: ZipFile.infolist()
159
160 Return a list containing a :class:`ZipInfo` object for each member of the
161 archive. The objects are in the same order as their entries in the actual ZIP
162 file on disk if an existing archive was opened.
163
164
165.. method:: ZipFile.namelist()
166
167 Return a list of archive members by name.
168
169
170.. method:: ZipFile.open(name[, mode[, pwd]])
171
172 Extract a member from the archive as a file-like object (ZipExtFile). *name* is
Georg Brandl112aa502008-05-20 08:25:48 +0000173 the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
174 parameter, if included, must be one of the following: ``'r'`` (the default),
175 ``'U'``, or ``'rU'``. Choosing ``'U'`` or ``'rU'`` will enable universal newline
176 support in the read-only object. *pwd* is the password used for encrypted files.
177 Calling :meth:`open` on a closed ZipFile will raise a :exc:`RuntimeError`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000178
179 .. note::
180
181 The file-like object is read-only and provides the following methods:
Georg Brandl52f83952011-02-25 10:39:23 +0000182 :meth:`!read`, :meth:`!readline`, :meth:`!readlines`, :meth:`!__iter__`,
183 :meth:`!next`.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000184
185 .. note::
186
187 If the ZipFile was created by passing in a file-like object as the first
Georg Brandl7f758c42007-08-15 18:41:25 +0000188 argument to the constructor, then the object returned by :meth:`.open` shares the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000189 ZipFile's file pointer. Under these circumstances, the object returned by
Georg Brandl7f758c42007-08-15 18:41:25 +0000190 :meth:`.open` should not be used after any additional operations are performed
Georg Brandl8ec7f652007-08-15 14:28:01 +0000191 on the ZipFile object. If the ZipFile was created by passing in a string (the
Georg Brandl7f758c42007-08-15 18:41:25 +0000192 filename) as the first argument to the constructor, then :meth:`.open` will
Georg Brandl8ec7f652007-08-15 14:28:01 +0000193 create a new file object that will be held by the ZipExtFile, allowing it to
194 operate independently of the ZipFile.
195
Georg Brandl112aa502008-05-20 08:25:48 +0000196 .. note::
197
198 The :meth:`open`, :meth:`read` and :meth:`extract` methods can take a filename
199 or a :class:`ZipInfo` object. You will appreciate this when trying to read a
200 ZIP file that contains members with duplicate names.
201
Georg Brandl8ec7f652007-08-15 14:28:01 +0000202 .. versionadded:: 2.6
203
204
Georg Brandl62416bc2008-01-07 18:47:44 +0000205.. method:: ZipFile.extract(member[, path[, pwd]])
206
Georg Brandl112aa502008-05-20 08:25:48 +0000207 Extract a member from the archive to the current working directory; *member*
208 must be its full name or a :class:`ZipInfo` object). Its file information is
209 extracted as accurately as possible. *path* specifies a different directory
210 to extract to. *member* can be a filename or a :class:`ZipInfo` object.
211 *pwd* is the password used for encrypted files.
Georg Brandl62416bc2008-01-07 18:47:44 +0000212
213 .. versionadded:: 2.6
214
215
216.. method:: ZipFile.extractall([path[, members[, pwd]]])
217
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000218 Extract all members from the archive to the current working directory. *path*
Georg Brandl62416bc2008-01-07 18:47:44 +0000219 specifies a different directory to extract to. *members* is optional and must
220 be a subset of the list returned by :meth:`namelist`. *pwd* is the password
221 used for encrypted files.
222
Gregory P. Smith657024c2009-09-29 21:56:31 +0000223 .. warning::
224
225 Never extract archives from untrusted sources without prior inspection.
226 It is possible that files are created outside of *path*, e.g. members
227 that have absolute filenames starting with ``"/"`` or filenames with two
228 dots ``".."``.
229
Georg Brandl62416bc2008-01-07 18:47:44 +0000230 .. versionadded:: 2.6
231
232
Georg Brandl8ec7f652007-08-15 14:28:01 +0000233.. method:: ZipFile.printdir()
234
235 Print a table of contents for the archive to ``sys.stdout``.
236
237
238.. method:: ZipFile.setpassword(pwd)
239
240 Set *pwd* as default password to extract encrypted files.
241
242 .. versionadded:: 2.6
243
244
245.. method:: ZipFile.read(name[, pwd])
246
Georg Brandl112aa502008-05-20 08:25:48 +0000247 Return the bytes of the file *name* in the archive. *name* is the name of the
248 file in the archive, or a :class:`ZipInfo` object. The archive must be open for
249 read or append. *pwd* is the password used for encrypted files and, if specified,
250 it will override the default password set with :meth:`setpassword`. Calling
Georg Brandl8ec7f652007-08-15 14:28:01 +0000251 :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`.
252
253 .. versionchanged:: 2.6
Georg Brandl112aa502008-05-20 08:25:48 +0000254 *pwd* was added, and *name* can now be a :class:`ZipInfo` object.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000255
256
257.. method:: ZipFile.testzip()
258
259 Read all the files in the archive and check their CRC's and file headers.
260 Return the name of the first bad file, or else return ``None``. Calling
261 :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
262
263
264.. method:: ZipFile.write(filename[, arcname[, compress_type]])
265
266 Write the file named *filename* to the archive, giving it the archive name
267 *arcname* (by default, this will be the same as *filename*, but without a drive
268 letter and with leading path separators removed). If given, *compress_type*
269 overrides the value given for the *compression* parameter to the constructor for
270 the new entry. The archive must be open with mode ``'w'`` or ``'a'`` -- calling
271 :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
272 :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a
273 :exc:`RuntimeError`.
274
275 .. note::
276
277 There is no official file name encoding for ZIP files. If you have unicode file
Georg Brandlf11ed152007-08-30 10:09:42 +0000278 names, you must convert them to byte strings in your desired encoding before
Georg Brandl8ec7f652007-08-15 14:28:01 +0000279 passing them to :meth:`write`. WinZip interprets all file names as encoded in
280 CP437, also known as DOS Latin.
281
282 .. note::
283
284 Archive names should be relative to the archive root, that is, they should not
285 start with a path separator.
286
287 .. note::
288
289 If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
290 byte, the name of the file in the archive will be truncated at the null byte.
291
292
Ronald Oussorendd25e862010-02-07 20:18:02 +0000293.. method:: ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294
295 Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
296 name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
297 an instance, at least the filename, date, and time must be given. If it's a
298 name, the date and time is set to the current date and time. The archive must be
299 opened with mode ``'w'`` or ``'a'`` -- calling :meth:`writestr` on a ZipFile
300 created with mode ``'r'`` will raise a :exc:`RuntimeError`. Calling
301 :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`.
302
Ronald Oussorendd25e862010-02-07 20:18:02 +0000303 If given, *compress_type* overrides the value given for the *compression*
304 parameter to the constructor for the new entry, or in the *zinfo_or_arcname*
305 (if that is a :class:`ZipInfo` instance).
306
Georg Brandl62416bc2008-01-07 18:47:44 +0000307 .. note::
308
Éric Araujo8e726b42010-12-26 17:55:02 +0000309 When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* parameter,
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000310 the compression method used will be that specified in the *compress_type*
311 member of the given :class:`ZipInfo` instance. By default, the
Georg Brandl62416bc2008-01-07 18:47:44 +0000312 :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
313
Ronald Oussorendd25e862010-02-07 20:18:02 +0000314 .. versionchanged:: 2.7
315 The *compression_type* argument.
316
Martin v. Löwis8c436412008-07-03 12:51:14 +0000317The following data attributes are also available:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000318
319
320.. attribute:: ZipFile.debug
321
322 The level of debug output to use. This may be set from ``0`` (the default, no
323 output) to ``3`` (the most output). Debugging information is written to
324 ``sys.stdout``.
325
Martin v. Löwis8c436412008-07-03 12:51:14 +0000326.. attribute:: ZipFile.comment
327
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000328 The comment text associated with the ZIP file. If assigning a comment to a
329 :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
330 string no longer than 65535 bytes. Comments longer than this will be
Martin v. Löwis8c436412008-07-03 12:51:14 +0000331 truncated in the written archive when :meth:`ZipFile.close` is called.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000332
333.. _pyzipfile-objects:
334
335PyZipFile Objects
336-----------------
337
338The :class:`PyZipFile` constructor takes the same parameters as the
339:class:`ZipFile` constructor. Instances have one method in addition to those of
340:class:`ZipFile` objects.
341
342
343.. method:: PyZipFile.writepy(pathname[, basename])
344
345 Search for files :file:`\*.py` and add the corresponding file to the archive.
346 The corresponding file is a :file:`\*.pyo` file if available, else a
347 :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
348 filename must end with :file:`.py`, and just the (corresponding
349 :file:`\*.py[co]`) file is added at the top level (no path information). If the
350 pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
351 will be raised. If it is a directory, and the directory is not a package
352 directory, then all the files :file:`\*.py[co]` are added at the top level. If
353 the directory is a package directory, then all :file:`\*.py[co]` are added under
354 the package name as a file path, and if any subdirectories are package
355 directories, all of these are added recursively. *basename* is intended for
356 internal use only. The :meth:`writepy` method makes archives with file names
357 like this::
358
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000359 string.pyc # Top level name
360 test/__init__.pyc # Package directory
Brett Cannon3c759142008-05-09 05:25:37 +0000361 test/test_support.pyc # Module test.test_support
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000362 test/bogus/__init__.pyc # Subpackage directory
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363 test/bogus/myfile.pyc # Submodule test.bogus.myfile
364
365
366.. _zipinfo-objects:
367
368ZipInfo Objects
369---------------
370
371Instances of the :class:`ZipInfo` class are returned by the :meth:`getinfo` and
372:meth:`infolist` methods of :class:`ZipFile` objects. Each object stores
373information about a single member of the ZIP archive.
374
375Instances have the following attributes:
376
377
378.. attribute:: ZipInfo.filename
379
380 Name of the file in the archive.
381
382
383.. attribute:: ZipInfo.date_time
384
385 The time and date of the last modification to the archive member. This is a
386 tuple of six values:
387
388 +-------+--------------------------+
389 | Index | Value |
390 +=======+==========================+
391 | ``0`` | Year |
392 +-------+--------------------------+
393 | ``1`` | Month (one-based) |
394 +-------+--------------------------+
395 | ``2`` | Day of month (one-based) |
396 +-------+--------------------------+
397 | ``3`` | Hours (zero-based) |
398 +-------+--------------------------+
399 | ``4`` | Minutes (zero-based) |
400 +-------+--------------------------+
401 | ``5`` | Seconds (zero-based) |
402 +-------+--------------------------+
403
404
405.. attribute:: ZipInfo.compress_type
406
407 Type of compression for the archive member.
408
409
410.. attribute:: ZipInfo.comment
411
412 Comment for the individual archive member.
413
414
415.. attribute:: ZipInfo.extra
416
417 Expansion field data. The `PKZIP Application Note
Georg Brandl02677812008-03-15 00:20:19 +0000418 <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
Georg Brandl8ec7f652007-08-15 14:28:01 +0000419 some comments on the internal structure of the data contained in this string.
420
421
422.. attribute:: ZipInfo.create_system
423
424 System which created ZIP archive.
425
426
427.. attribute:: ZipInfo.create_version
428
429 PKZIP version which created ZIP archive.
430
431
432.. attribute:: ZipInfo.extract_version
433
434 PKZIP version needed to extract archive.
435
436
437.. attribute:: ZipInfo.reserved
438
439 Must be zero.
440
441
442.. attribute:: ZipInfo.flag_bits
443
444 ZIP flag bits.
445
446
447.. attribute:: ZipInfo.volume
448
449 Volume number of file header.
450
451
452.. attribute:: ZipInfo.internal_attr
453
454 Internal attributes.
455
456
457.. attribute:: ZipInfo.external_attr
458
459 External file attributes.
460
461
462.. attribute:: ZipInfo.header_offset
463
464 Byte offset to the file header.
465
466
467.. attribute:: ZipInfo.CRC
468
469 CRC-32 of the uncompressed file.
470
471
472.. attribute:: ZipInfo.compress_size
473
474 Size of the compressed data.
475
476
477.. attribute:: ZipInfo.file_size
478
479 Size of the uncompressed file.
480