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