blob: 3e6448725701ce04166e0537c69727b838e234b5 [file] [log] [blame]
Andrew Hsieh9a7616f2013-05-21 20:32:42 +08001: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
9.. versionadded:: 1.6
10
11**Source code:** :source:`Lib/zipfile.py`
12
13--------------
14
15The 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
19<http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_.
20
21This module does not currently handle multi-disk ZIP files.
22It can handle ZIP files that use the ZIP64 extensions
23(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
25create an encrypted file. Decryption is extremely slow as it is
26implemented in native Python rather than C.
27
28The module defines the following items:
29
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 :noindex:
43
44 The class for reading and writing ZIP files. See section
45 :ref:`zipfile-objects` for constructor details.
46
47
48.. class:: PyZipFile
49
50 Class for creating ZIP archives containing Python libraries.
51
52
53.. class:: ZipInfo([filename[, date_time]])
54
55 Class used to represent information about a member of an archive. Instances
56 of this class are returned by the :meth:`.getinfo` and :meth:`.infolist`
57 methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
58 will not need to create these, but only use those created by this
59 module. *filename* should be the full name of the archive member, and
60 *date_time* should be a tuple containing six fields which describe the time
61 of the last modification to the file; the fields are described in section
62 :ref:`zipinfo-objects`.
63
64
65.. function:: is_zipfile(filename)
66
67 Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
68 otherwise returns ``False``. *filename* may be a file or file-like object too.
69
70 .. versionchanged:: 2.7
71 Support for file and file-like objects.
72
73.. data:: ZIP_STORED
74
75 The numeric constant for an uncompressed archive member.
76
77
78.. data:: ZIP_DEFLATED
79
80 The numeric constant for the usual ZIP compression method. This requires the
81 :mod:`zlib` module. No other compression methods are currently supported.
82
83
84.. seealso::
85
86 `PKZIP Application Note <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_
87 Documentation on the ZIP file format by Phil Katz, the creator of the format and
88 algorithms used.
89
90 `Info-ZIP Home Page <http://www.info-zip.org/>`_
91 Information about the Info-ZIP project's ZIP archive programs and development
92 libraries.
93
94
95.. _zipfile-objects:
96
97ZipFile Objects
98---------------
99
100
101.. class:: ZipFile(file[, mode[, compression[, allowZip64]]])
102
103 Open a ZIP file, where *file* can be either a path to a file (a string) or a
104 file-like object. The *mode* parameter should be ``'r'`` to read an existing
105 file, ``'w'`` to truncate and write a new file, or ``'a'`` to append to an
106 existing file. If *mode* is ``'a'`` and *file* refers to an existing ZIP
107 file, then additional files are added to it. If *file* does not refer to a
108 ZIP file, then a new ZIP archive is appended to the file. This is meant for
109 adding a ZIP archive to another file (such as :file:`python.exe`).
110
111 .. versionchanged:: 2.6
112 If *mode* is ``a`` and the file does not exist at all, it is created.
113
114 *compression* is the ZIP compression method to use when writing the archive,
115 and should be :const:`ZIP_STORED` or :const:`ZIP_DEFLATED`; unrecognized
116 values will cause :exc:`RuntimeError` to be raised. If :const:`ZIP_DEFLATED`
117 is specified but the :mod:`zlib` module is not available, :exc:`RuntimeError`
118 is also raised. The default is :const:`ZIP_STORED`. If *allowZip64* is
119 ``True`` zipfile will create ZIP files that use the ZIP64 extensions when
120 the zipfile is larger than 2 GB. If it is false (the default) :mod:`zipfile`
121 will raise an exception when the ZIP file would require ZIP64 extensions.
122 ZIP64 extensions are disabled by default because the default :program:`zip`
123 and :program:`unzip` commands on Unix (the InfoZIP utilities) don't support
124 these extensions.
125
126 .. versionchanged:: 2.7.1
127 If the file is created with mode ``'a'`` or ``'w'`` and then
128 :meth:`closed <close>` without adding any files to the archive, the appropriate
129 ZIP structures for an empty archive will be written to the file.
130
131 ZipFile is also a context manager and therefore supports the
132 :keyword:`with` statement. In the example, *myzip* is closed after the
133 :keyword:`with` statement's suite is finished---even if an exception occurs::
134
135 with ZipFile('spam.zip', 'w') as myzip:
136 myzip.write('eggs.txt')
137
138 .. versionadded:: 2.7
139 Added the ability to use :class:`ZipFile` as a context manager.
140
141
142.. method:: ZipFile.close()
143
144 Close the archive file. You must call :meth:`close` before exiting your program
145 or essential records will not be written.
146
147
148.. method:: ZipFile.getinfo(name)
149
150 Return a :class:`ZipInfo` object with information about the archive member
151 *name*. Calling :meth:`getinfo` for a name not currently contained in the
152 archive will raise a :exc:`KeyError`.
153
154
155.. method:: ZipFile.infolist()
156
157 Return a list containing a :class:`ZipInfo` object for each member of the
158 archive. The objects are in the same order as their entries in the actual ZIP
159 file on disk if an existing archive was opened.
160
161
162.. method:: ZipFile.namelist()
163
164 Return a list of archive members by name.
165
166 .. index::
167 single: universal newlines; zipfile.ZipFile.open method
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
173 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
176 :term:`universal newline <universal newlines>`
177 support in the read-only object. *pwd* is the password used for encrypted files.
178 Calling :meth:`.open` on a closed ZipFile will raise a :exc:`RuntimeError`.
179
180 .. note::
181
182 The file-like object is read-only and provides the following methods:
183 :meth:`!read`, :meth:`!readline`, :meth:`!readlines`, :meth:`!__iter__`,
184 :meth:`!next`.
185
186 .. note::
187
188 If the ZipFile was created by passing in a file-like object as the first
189 argument to the constructor, then the object returned by :meth:`.open` shares the
190 ZipFile's file pointer. Under these circumstances, the object returned by
191 :meth:`.open` should not be used after any additional operations are performed
192 on the ZipFile object. If the ZipFile was created by passing in a string (the
193 filename) as the first argument to the constructor, then :meth:`.open` will
194 create a new file object that will be held by the ZipExtFile, allowing it to
195 operate independently of the ZipFile.
196
197 .. note::
198
199 The :meth:`.open`, :meth:`read` and :meth:`extract` methods can take a filename
200 or a :class:`ZipInfo` object. You will appreciate this when trying to read a
201 ZIP file that contains members with duplicate names.
202
203 .. versionadded:: 2.6
204
205
206.. method:: ZipFile.extract(member[, path[, pwd]])
207
208 Extract a member from the archive to the current working directory; *member*
209 must be its full name or a :class:`ZipInfo` object). Its file information is
210 extracted as accurately as possible. *path* specifies a different directory
211 to extract to. *member* can be a filename or a :class:`ZipInfo` object.
212 *pwd* is the password used for encrypted files.
213
214 .. versionadded:: 2.6
215
216 .. note::
217
218 If a member filename is an absolute path, a drive/UNC sharepoint and
219 leading (back)slashes will be stripped, e.g.: ``///foo/bar`` becomes
220 ``foo/bar`` on Unix, and ``C:\foo\bar`` becomes ``foo\bar`` on Windows.
221 And all ``".."`` components in a member filename will be removed, e.g.:
222 ``../../foo../../ba..r`` becomes ``foo../ba..r``. On Windows illegal
223 characters (``:``, ``<``, ``>``, ``|``, ``"``, ``?``, and ``*``)
224 replaced by underscore (``_``).
225
226
227.. method:: ZipFile.extractall([path[, members[, pwd]]])
228
229 Extract all members from the archive to the current working directory. *path*
230 specifies a different directory to extract to. *members* is optional and must
231 be a subset of the list returned by :meth:`namelist`. *pwd* is the password
232 used for encrypted files.
233
234 .. warning::
235
236 Never extract archives from untrusted sources without prior inspection.
237 It is possible that files are created outside of *path*, e.g. members
238 that have absolute filenames starting with ``"/"`` or filenames with two
239 dots ``".."``.
240
241 .. versionchanged:: 2.7.4
242 The zipfile module attempts to prevent that. See :meth:`extract` note.
243
244 .. versionadded:: 2.6
245
246
247.. method:: ZipFile.printdir()
248
249 Print a table of contents for the archive to ``sys.stdout``.
250
251
252.. method:: ZipFile.setpassword(pwd)
253
254 Set *pwd* as default password to extract encrypted files.
255
256 .. versionadded:: 2.6
257
258
259.. method:: ZipFile.read(name[, pwd])
260
261 Return the bytes of the file *name* in the archive. *name* is the name of the
262 file in the archive, or a :class:`ZipInfo` object. The archive must be open for
263 read or append. *pwd* is the password used for encrypted files and, if specified,
264 it will override the default password set with :meth:`setpassword`. Calling
265 :meth:`read` on a closed ZipFile will raise a :exc:`RuntimeError`.
266
267 .. versionchanged:: 2.6
268 *pwd* was added, and *name* can now be a :class:`ZipInfo` object.
269
270
271.. method:: ZipFile.testzip()
272
273 Read all the files in the archive and check their CRC's and file headers.
274 Return the name of the first bad file, or else return ``None``. Calling
275 :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.
276
277
278.. method:: ZipFile.write(filename[, arcname[, compress_type]])
279
280 Write the file named *filename* to the archive, giving it the archive name
281 *arcname* (by default, this will be the same as *filename*, but without a drive
282 letter and with leading path separators removed). If given, *compress_type*
283 overrides the value given for the *compression* parameter to the constructor for
284 the new entry. The archive must be open with mode ``'w'`` or ``'a'`` -- calling
285 :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
286 :exc:`RuntimeError`. Calling :meth:`write` on a closed ZipFile will raise a
287 :exc:`RuntimeError`.
288
289 .. note::
290
291 There is no official file name encoding for ZIP files. If you have unicode file
292 names, you must convert them to byte strings in your desired encoding before
293 passing them to :meth:`write`. WinZip interprets all file names as encoded in
294 CP437, also known as DOS Latin.
295
296 .. note::
297
298 Archive names should be relative to the archive root, that is, they should not
299 start with a path separator.
300
301 .. note::
302
303 If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
304 byte, the name of the file in the archive will be truncated at the null byte.
305
306
307.. method:: ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])
308
309 Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
310 name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
311 an instance, at least the filename, date, and time must be given. If it's a
312 name, the date and time is set to the current date and time. The archive must be
313 opened with mode ``'w'`` or ``'a'`` -- calling :meth:`writestr` on a ZipFile
314 created with mode ``'r'`` will raise a :exc:`RuntimeError`. Calling
315 :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`.
316
317 If given, *compress_type* overrides the value given for the *compression*
318 parameter to the constructor for the new entry, or in the *zinfo_or_arcname*
319 (if that is a :class:`ZipInfo` instance).
320
321 .. note::
322
323 When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* parameter,
324 the compression method used will be that specified in the *compress_type*
325 member of the given :class:`ZipInfo` instance. By default, the
326 :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
327
328 .. versionchanged:: 2.7
329 The *compress_type* argument.
330
331The following data attributes are also available:
332
333
334.. attribute:: ZipFile.debug
335
336 The level of debug output to use. This may be set from ``0`` (the default, no
337 output) to ``3`` (the most output). Debugging information is written to
338 ``sys.stdout``.
339
340.. attribute:: ZipFile.comment
341
342 The comment text associated with the ZIP file. If assigning a comment to a
343 :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
344 string no longer than 65535 bytes. Comments longer than this will be
345 truncated in the written archive when :meth:`.close` is called.
346
347.. _pyzipfile-objects:
348
349PyZipFile Objects
350-----------------
351
352The :class:`PyZipFile` constructor takes the same parameters as the
353:class:`ZipFile` constructor. Instances have one method in addition to those of
354:class:`ZipFile` objects.
355
356
357.. method:: PyZipFile.writepy(pathname[, basename])
358
359 Search for files :file:`\*.py` and add the corresponding file to the archive.
360 The corresponding file is a :file:`\*.pyo` file if available, else a
361 :file:`\*.pyc` file, compiling if necessary. If the pathname is a file, the
362 filename must end with :file:`.py`, and just the (corresponding
363 :file:`\*.py[co]`) file is added at the top level (no path information). If the
364 pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
365 will be raised. If it is a directory, and the directory is not a package
366 directory, then all the files :file:`\*.py[co]` are added at the top level. If
367 the directory is a package directory, then all :file:`\*.py[co]` are added under
368 the package name as a file path, and if any subdirectories are package
369 directories, all of these are added recursively. *basename* is intended for
370 internal use only. The :meth:`writepy` method makes archives with file names
371 like this::
372
373 string.pyc # Top level name
374 test/__init__.pyc # Package directory
375 test/test_support.pyc # Module test.test_support
376 test/bogus/__init__.pyc # Subpackage directory
377 test/bogus/myfile.pyc # Submodule test.bogus.myfile
378
379
380.. _zipinfo-objects:
381
382ZipInfo Objects
383---------------
384
385Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
386:meth:`.infolist` methods of :class:`ZipFile` objects. Each object stores
387information about a single member of the ZIP archive.
388
389Instances have the following attributes:
390
391
392.. attribute:: ZipInfo.filename
393
394 Name of the file in the archive.
395
396
397.. attribute:: ZipInfo.date_time
398
399 The time and date of the last modification to the archive member. This is a
400 tuple of six values:
401
402 +-------+--------------------------+
403 | Index | Value |
404 +=======+==========================+
405 | ``0`` | Year (>= 1980) |
406 +-------+--------------------------+
407 | ``1`` | Month (one-based) |
408 +-------+--------------------------+
409 | ``2`` | Day of month (one-based) |
410 +-------+--------------------------+
411 | ``3`` | Hours (zero-based) |
412 +-------+--------------------------+
413 | ``4`` | Minutes (zero-based) |
414 +-------+--------------------------+
415 | ``5`` | Seconds (zero-based) |
416 +-------+--------------------------+
417
418 .. note::
419
420 The ZIP file format does not support timestamps before 1980.
421
422
423.. attribute:: ZipInfo.compress_type
424
425 Type of compression for the archive member.
426
427
428.. attribute:: ZipInfo.comment
429
430 Comment for the individual archive member.
431
432
433.. attribute:: ZipInfo.extra
434
435 Expansion field data. The `PKZIP Application Note
436 <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>`_ contains
437 some comments on the internal structure of the data contained in this string.
438
439
440.. attribute:: ZipInfo.create_system
441
442 System which created ZIP archive.
443
444
445.. attribute:: ZipInfo.create_version
446
447 PKZIP version which created ZIP archive.
448
449
450.. attribute:: ZipInfo.extract_version
451
452 PKZIP version needed to extract archive.
453
454
455.. attribute:: ZipInfo.reserved
456
457 Must be zero.
458
459
460.. attribute:: ZipInfo.flag_bits
461
462 ZIP flag bits.
463
464
465.. attribute:: ZipInfo.volume
466
467 Volume number of file header.
468
469
470.. attribute:: ZipInfo.internal_attr
471
472 Internal attributes.
473
474
475.. attribute:: ZipInfo.external_attr
476
477 External file attributes.
478
479
480.. attribute:: ZipInfo.header_offset
481
482 Byte offset to the file header.
483
484
485.. attribute:: ZipInfo.CRC
486
487 CRC-32 of the uncompressed file.
488
489
490.. attribute:: ZipInfo.compress_size
491
492 Size of the compressed data.
493
494
495.. attribute:: ZipInfo.file_size
496
497 Size of the uncompressed file.
498