Debian Codegraph @

Doc/library/zipfile.rst

raw
1 :mod:`!zipfile` --- Work with ZIP archives
2 ==========================================
3
4 .. module:: zipfile
5 :synopsis: Read and write ZIP-format archive files.
6
7 .. moduleauthor:: James C. Ahlstrom <[email protected]>
8 .. sectionauthor:: James C. Ahlstrom <[email protected]>
9
10 **Source code:** :source:`Lib/zipfile/`
11
12 --------------
13
14 The ZIP file format is a common archive and compression standard. This module
15 provides tools to create, read, write, append, and list a ZIP file. Any
16 advanced use of this module will require an understanding of the format, as
17 defined in `PKZIP Application Note`_.
18
19 This module does not handle multipart ZIP files.
20 It can handle ZIP files that use the ZIP64 extensions
21 (that is ZIP files that are more than 4 GiB in size). It supports
22 decryption of encrypted files in ZIP archives, but it cannot
23 create an encrypted file. Decryption is extremely slow as it is
24 implemented in native Python rather than C.
25
26 The module defines the following items:
27
28 .. exception:: BadZipFile
29
30 The error raised for bad ZIP files.
31
32 .. versionadded:: 3.2
33
34
35 .. exception:: BadZipfile
36
37 Alias of :exc:`BadZipFile`, for compatibility with older Python versions.
38
39 .. deprecated:: 3.2
40
41
42 .. exception:: LargeZipFile
43
44 The error raised when a ZIP file would require ZIP64 functionality but that has
45 not been enabled.
46
47
48 .. class:: ZipFile
49 :noindex:
50
51 The class for reading and writing ZIP files. See section
52 :ref:`zipfile-objects` for constructor details.
53
54
55 .. class:: Path
56 :noindex:
57
58 Class that implements a subset of the interface provided by
59 :class:`pathlib.Path`, including the full
60 :class:`importlib.resources.abc.Traversable` interface.
61
62 .. versionadded:: 3.8
63
64
65 .. class:: PyZipFile
66 :noindex:
67
68 Class for creating ZIP archives containing Python libraries.
69
70
71 .. class:: ZipInfo(filename='NoName', date_time=(1980,1,1,0,0,0))
72
73 Class used to represent information about a member of an archive. Instances
74 of this class are returned by the :meth:`.getinfo` and :meth:`.infolist`
75 methods of :class:`ZipFile` objects. Most users of the :mod:`zipfile` module
76 will not need to create these, but only use those created by this
77 module. *filename* should be the full name of the archive member, and
78 *date_time* should be a tuple containing six fields which describe the time
79 of the last modification to the file; the fields are described in section
80 :ref:`zipinfo-objects`.
81
82 .. versionchanged:: 3.13
83 A public :attr:`!compress_level` attribute has been added to expose the
84 formerly protected :attr:`!_compresslevel`. The older protected name
85 continues to work as a property for backwards compatibility.
86
87 .. function:: is_zipfile(filename)
88
89 Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
90 otherwise returns ``False``. *filename* may be a file or file-like object too.
91
92 .. versionchanged:: 3.1
93 Support for file and file-like objects.
94
95
96 .. data:: ZIP_STORED
97
98 The numeric constant for an uncompressed archive member.
99
100
101 .. data:: ZIP_DEFLATED
102
103 The numeric constant for the usual ZIP compression method. This requires the
104 :mod:`zlib` module.
105
106
107 .. data:: ZIP_BZIP2
108
109 The numeric constant for the BZIP2 compression method. This requires the
110 :mod:`bz2` module.
111
112 .. versionadded:: 3.3
113
114 .. data:: ZIP_LZMA
115
116 The numeric constant for the LZMA compression method. This requires the
117 :mod:`lzma` module.
118
119 .. versionadded:: 3.3
120
121 .. note::
122
123 The ZIP file format specification has included support for bzip2 compression
124 since 2001, and for LZMA compression since 2006. However, some tools
125 (including older Python releases) do not support these compression
126 methods, and may either refuse to process the ZIP file altogether,
127 or fail to extract individual files.
128
129
130 .. seealso::
131
132 `PKZIP Application Note`_
133 Documentation on the ZIP file format by Phil Katz, the creator of the format and
134 algorithms used.
135
136 `Info-ZIP Home Page <https://infozip.sourceforge.net/>`_
137 Information about the Info-ZIP project's ZIP archive programs and development
138 libraries.
139
140
141 .. _zipfile-objects:
142
143 ZipFile objects
144 ---------------
145
146
147 .. class:: ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, \
148 compresslevel=None, *, strict_timestamps=True, \
149 metadata_encoding=None)
150
151 Open a ZIP file, where *file* can be a path to a file (a string), a
152 file-like object or a :term:`path-like object`.
153
154 The *mode* parameter should be ``'r'`` to read an existing
155 file, ``'w'`` to truncate and write a new file, ``'a'`` to append to an
156 existing file, or ``'x'`` to exclusively create and write a new file.
157 If *mode* is ``'x'`` and *file* refers to an existing file,
158 a :exc:`FileExistsError` will be raised.
159 If *mode* is ``'a'`` and *file* refers to an existing ZIP
160 file, then additional files are added to it. If *file* does not refer to a
161 ZIP file, then a new ZIP archive is appended to the file. This is meant for
162 adding a ZIP archive to another file (such as :file:`python.exe`). If
163 *mode* is ``'a'`` and the file does not exist at all, it is created.
164 If *mode* is ``'r'`` or ``'a'``, the file should be seekable.
165
166 *compression* is the ZIP compression method to use when writing the archive,
167 and should be :const:`ZIP_STORED`, :const:`ZIP_DEFLATED`,
168 :const:`ZIP_BZIP2` or :const:`ZIP_LZMA`; unrecognized
169 values will cause :exc:`NotImplementedError` to be raised. If
170 :const:`ZIP_DEFLATED`, :const:`ZIP_BZIP2` or :const:`ZIP_LZMA` is specified
171 but the corresponding module (:mod:`zlib`, :mod:`bz2` or :mod:`lzma`) is not
172 available, :exc:`RuntimeError` is raised. The default is :const:`ZIP_STORED`.
173
174 If *allowZip64* is ``True`` (the default) zipfile will create ZIP files that
175 use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is
176 ``false`` :mod:`zipfile` will raise an exception when the ZIP file would
177 require ZIP64 extensions.
178
179 The *compresslevel* parameter controls the compression level to use when
180 writing files to the archive.
181 When using :const:`ZIP_STORED` or :const:`ZIP_LZMA` it has no effect.
182 When using :const:`ZIP_DEFLATED` integers ``0`` through ``9`` are accepted
183 (see :class:`zlib <zlib.compressobj>` for more information).
184 When using :const:`ZIP_BZIP2` integers ``1`` through ``9`` are accepted
185 (see :class:`bz2 <bz2.BZ2File>` for more information).
186
187 The *strict_timestamps* argument, when set to ``False``, allows to
188 zip files older than 1980-01-01 at the cost of setting the
189 timestamp to 1980-01-01.
190 Similar behavior occurs with files newer than 2107-12-31,
191 the timestamp is also set to the limit.
192
193 When mode is ``'r'``, *metadata_encoding* may be set to the name of a codec,
194 which will be used to decode metadata such as the names of members and ZIP
195 comments.
196
197 If the file is created with mode ``'w'``, ``'x'`` or ``'a'`` and then
198 :meth:`closed <close>` without adding any files to the archive, the appropriate
199 ZIP structures for an empty archive will be written to the file.
200
201 ZipFile is also a context manager and therefore supports the
202 :keyword:`with` statement. In the example, *myzip* is closed after the
203 :keyword:`!with` statement's suite is finished---even if an exception occurs::
204
205 with ZipFile('spam.zip', 'w') as myzip:
206 myzip.write('eggs.txt')
207
208 .. note::
209
210 *metadata_encoding* is an instance-wide setting for the ZipFile.
211 It is not possible to set this on a per-member basis.
212
213 This attribute is a workaround for legacy implementations which produce
214 archives with names in the current locale encoding or code page (mostly
215 on Windows). According to the .ZIP standard, the encoding of metadata
216 may be specified to be either IBM code page (default) or UTF-8 by a flag
217 in the archive header.
218 That flag takes precedence over *metadata_encoding*, which is
219 a Python-specific extension.
220
221 .. versionchanged:: 3.2
222 Added the ability to use :class:`ZipFile` as a context manager.
223
224 .. versionchanged:: 3.3
225 Added support for :mod:`bzip2 <bz2>` and :mod:`lzma` compression.
226
227 .. versionchanged:: 3.4
228 ZIP64 extensions are enabled by default.
229
230 .. versionchanged:: 3.5
231 Added support for writing to unseekable streams.
232 Added support for the ``'x'`` mode.
233
234 .. versionchanged:: 3.6
235 Previously, a plain :exc:`RuntimeError` was raised for unrecognized
236 compression values.
237
238 .. versionchanged:: 3.6.2
239 The *file* parameter accepts a :term:`path-like object`.
240
241 .. versionchanged:: 3.7
242 Add the *compresslevel* parameter.
243
244 .. versionchanged:: 3.8
245 The *strict_timestamps* keyword-only parameter.
246
247 .. versionchanged:: 3.11
248 Added support for specifying member name encoding for reading
249 metadata in the zipfile's directory and file headers.
250
251
252 .. method:: ZipFile.close()
253
254 Close the archive file. You must call :meth:`close` before exiting your program
255 or essential records will not be written.
256
257
258 .. method:: ZipFile.getinfo(name)
259
260 Return a :class:`ZipInfo` object with information about the archive member
261 *name*. Calling :meth:`getinfo` for a name not currently contained in the
262 archive will raise a :exc:`KeyError`.
263
264
265 .. method:: ZipFile.infolist()
266
267 Return a list containing a :class:`ZipInfo` object for each member of the
268 archive. The objects are in the same order as their entries in the actual ZIP
269 file on disk if an existing archive was opened.
270
271
272 .. method:: ZipFile.namelist()
273
274 Return a list of archive members by name.
275
276
277 .. method:: ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)
278
279 Access a member of the archive as a binary file-like object. *name*
280 can be either the name of a file within the archive or a :class:`ZipInfo`
281 object. The *mode* parameter, if included, must be ``'r'`` (the default)
282 or ``'w'``. *pwd* is the password used to decrypt encrypted ZIP files as a
283 :class:`bytes` object.
284
285 :meth:`~ZipFile.open` is also a context manager and therefore supports the
286 :keyword:`with` statement::
287
288 with ZipFile('spam.zip') as myzip:
289 with myzip.open('eggs.txt') as myfile:
290 print(myfile.read())
291
292 With *mode* ``'r'`` the file-like object
293 (``ZipExtFile``) is read-only and provides the following methods:
294 :meth:`~io.BufferedIOBase.read`, :meth:`~io.IOBase.readline`,
295 :meth:`~io.IOBase.readlines`, :meth:`~io.IOBase.seek`,
296 :meth:`~io.IOBase.tell`, :meth:`~container.__iter__`, :meth:`~iterator.__next__`.
297 These objects can operate independently of the ZipFile.
298
299 With ``mode='w'``, a writable file handle is returned, which supports the
300 :meth:`~io.BufferedIOBase.write` method. While a writable file handle is open,
301 attempting to read or write other files in the ZIP file will raise a
302 :exc:`ValueError`.
303
304 In both cases the file-like object has also attributes :attr:`!name`,
305 which is equivalent to the name of a file within the archive, and
306 :attr:`!mode`, which is ``'rb'`` or ``'wb'`` depending on the input mode.
307
308 When writing a file, if the file size is not known in advance but may exceed
309 2 GiB, pass ``force_zip64=True`` to ensure that the header format is
310 capable of supporting large files. If the file size is known in advance,
311 construct a :class:`ZipInfo` object with :attr:`~ZipInfo.file_size` set, and
312 use that as the *name* parameter.
313
314 .. note::
315
316 The :meth:`.open`, :meth:`read` and :meth:`extract` methods can take a filename
317 or a :class:`ZipInfo` object. You will appreciate this when trying to read a
318 ZIP file that contains members with duplicate names.
319
320 .. versionchanged:: 3.6
321 Removed support of ``mode='U'``. Use :class:`io.TextIOWrapper` for reading
322 compressed text files in :term:`universal newlines` mode.
323
324 .. versionchanged:: 3.6
325 :meth:`ZipFile.open` can now be used to write files into the archive with the
326 ``mode='w'`` option.
327
328 .. versionchanged:: 3.6
329 Calling :meth:`.open` on a closed ZipFile will raise a :exc:`ValueError`.
330 Previously, a :exc:`RuntimeError` was raised.
331
332 .. versionchanged:: 3.13
333 Added attributes :attr:`!name` and :attr:`!mode` for the writeable
334 file-like object.
335 The value of the :attr:`!mode` attribute for the readable file-like
336 object was changed from ``'r'`` to ``'rb'``.
337
338
339 .. method:: ZipFile.extract(member, path=None, pwd=None)
340
341 Extract a member from the archive to the current working directory; *member*
342 must be its full name or a :class:`ZipInfo` object. Its file information is
343 extracted as accurately as possible. *path* specifies a different directory
344 to extract to. *member* can be a filename or a :class:`ZipInfo` object.
345 *pwd* is the password used for encrypted files as a :class:`bytes` object.
346
347 Returns the normalized path created (a directory or new file).
348
349 .. note::
350
351 If a member filename is an absolute path, a drive/UNC sharepoint and
352 leading (back)slashes will be stripped, e.g.: ``///foo/bar`` becomes
353 ``foo/bar`` on Unix, and ``C:\foo\bar`` becomes ``foo\bar`` on Windows.
354 And all ``".."`` components in a member filename will be removed, e.g.:
355 ``../../foo../../ba..r`` becomes ``foo../ba..r``. On Windows illegal
356 characters (``:``, ``<``, ``>``, ``|``, ``"``, ``?``, and ``*``)
357 replaced by underscore (``_``).
358
359 .. versionchanged:: 3.6
360 Calling :meth:`extract` on a closed ZipFile will raise a
361 :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
362
363 .. versionchanged:: 3.6.2
364 The *path* parameter accepts a :term:`path-like object`.
365
366
367 .. method:: ZipFile.extractall(path=None, members=None, pwd=None)
368
369 Extract all members from the archive to the current working directory. *path*
370 specifies a different directory to extract to. *members* is optional and must
371 be a subset of the list returned by :meth:`namelist`. *pwd* is the password
372 used for encrypted files as a :class:`bytes` object.
373
374 .. warning::
375
376 Never extract archives from untrusted sources without prior inspection.
377 It is possible that files are created outside of *path*, for example, members
378 that have absolute filenames or filenames with ".." components.
379 This module attempts to prevent that.
380 See :meth:`extract` note.
381
382 .. versionchanged:: 3.6
383 Calling :meth:`extractall` on a closed ZipFile will raise a
384 :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
385
386 .. versionchanged:: 3.6.2
387 The *path* parameter accepts a :term:`path-like object`.
388
389
390 .. method:: ZipFile.printdir()
391
392 Print a table of contents for the archive to ``sys.stdout``.
393
394
395 .. method:: ZipFile.setpassword(pwd)
396
397 Set *pwd* (a :class:`bytes` object) as default password to extract encrypted files.
398
399
400 .. method:: ZipFile.read(name, pwd=None)
401
402 Return the bytes of the file *name* in the archive. *name* is the name of the
403 file in the archive, or a :class:`ZipInfo` object. The archive must be open for
404 read or append. *pwd* is the password used for encrypted files as a :class:`bytes`
405 object and, if specified, overrides the default password set with :meth:`setpassword`.
406 Calling :meth:`read` on a ZipFile that uses a compression method other than
407 :const:`ZIP_STORED`, :const:`ZIP_DEFLATED`, :const:`ZIP_BZIP2` or
408 :const:`ZIP_LZMA` will raise a :exc:`NotImplementedError`. An error will also
409 be raised if the corresponding compression module is not available.
410
411 .. versionchanged:: 3.6
412 Calling :meth:`read` on a closed ZipFile will raise a :exc:`ValueError`.
413 Previously, a :exc:`RuntimeError` was raised.
414
415
416 .. method:: ZipFile.testzip()
417
418 Read all the files in the archive and check their CRC's and file headers.
419 Return the name of the first bad file, or else return ``None``.
420
421 .. versionchanged:: 3.6
422 Calling :meth:`testzip` on a closed ZipFile will raise a
423 :exc:`ValueError`. Previously, a :exc:`RuntimeError` was raised.
424
425
426 .. method:: ZipFile.write(filename, arcname=None, compress_type=None, \
427 compresslevel=None)
428
429 Write the file named *filename* to the archive, giving it the archive name
430 *arcname* (by default, this will be the same as *filename*, but without a drive
431 letter and with leading path separators removed). If given, *compress_type*
432 overrides the value given for the *compression* parameter to the constructor for
433 the new entry. Similarly, *compresslevel* will override the constructor if
434 given.
435 The archive must be open with mode ``'w'``, ``'x'`` or ``'a'``.
436
437 .. note::
438
439 The ZIP file standard historically did not specify a metadata encoding,
440 but strongly recommended CP437 (the original IBM PC encoding) for
441 interoperability. Recent versions allow use of UTF-8 (only). In this
442 module, UTF-8 will automatically be used to write the member names if
443 they contain any non-ASCII characters. It is not possible to write
444 member names in any encoding other than ASCII or UTF-8.
445
446 .. note::
447
448 Archive names should be relative to the archive root, that is, they should not
449 start with a path separator.
450
451 .. note::
452
453 If ``arcname`` (or ``filename``, if ``arcname`` is not given) contains a null
454 byte, the name of the file in the archive will be truncated at the null byte.
455
456 .. note::
457
458 A leading slash in the filename may lead to the archive being impossible to
459 open in some zip programs on Windows systems.
460
461 .. versionchanged:: 3.6
462 Calling :meth:`write` on a ZipFile created with mode ``'r'`` or
463 a closed ZipFile will raise a :exc:`ValueError`. Previously,
464 a :exc:`RuntimeError` was raised.
465
466
467 .. method:: ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, \
468 compresslevel=None)
469
470 Write a file into the archive. The contents is *data*, which may be either
471 a :class:`str` or a :class:`bytes` instance; if it is a :class:`str`,
472 it is encoded as UTF-8 first. *zinfo_or_arcname* is either the file
473 name it will be given in the archive, or a :class:`ZipInfo` instance. If it's
474 an instance, at least the filename, date, and time must be given. If it's a
475 name, the date and time is set to the current date and time.
476 The archive must be opened with mode ``'w'``, ``'x'`` or ``'a'``.
477
478 If given, *compress_type* overrides the value given for the *compression*
479 parameter to the constructor for the new entry, or in the *zinfo_or_arcname*
480 (if that is a :class:`ZipInfo` instance). Similarly, *compresslevel* will
481 override the constructor if given.
482
483 .. note::
484
485 When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* parameter,
486 the compression method used will be that specified in the *compress_type*
487 member of the given :class:`ZipInfo` instance. By default, the
488 :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
489
490 .. versionchanged:: 3.2
491 The *compress_type* argument.
492
493 .. versionchanged:: 3.6
494 Calling :meth:`writestr` on a ZipFile created with mode ``'r'`` or
495 a closed ZipFile will raise a :exc:`ValueError`. Previously,
496 a :exc:`RuntimeError` was raised.
497
498 .. method:: ZipFile.mkdir(zinfo_or_directory, mode=511)
499
500 Create a directory inside the archive. If *zinfo_or_directory* is a string,
501 a directory is created inside the archive with the mode that is specified in
502 the *mode* argument. If, however, *zinfo_or_directory* is
503 a :class:`ZipInfo` instance then the *mode* argument is ignored.
504
505 The archive must be opened with mode ``'w'``, ``'x'`` or ``'a'``.
506
507 .. versionadded:: 3.11
508
509
510 The following data attributes are also available:
511
512 .. attribute:: ZipFile.filename
513
514 Name of the ZIP file.
515
516 .. attribute:: ZipFile.debug
517
518 The level of debug output to use. This may be set from ``0`` (the default, no
519 output) to ``3`` (the most output). Debugging information is written to
520 ``sys.stdout``.
521
522 .. attribute:: ZipFile.comment
523
524 The comment associated with the ZIP file as a :class:`bytes` object.
525 If assigning a comment to a
526 :class:`ZipFile` instance created with mode ``'w'``, ``'x'`` or ``'a'``,
527 it should be no longer than 65535 bytes. Comments longer than this will be
528 truncated.
529
530
531 .. _path-objects:
532
533 Path objects
534 ------------
535
536 .. class:: Path(root, at='')
537
538 Construct a Path object from a ``root`` zipfile (which may be a
539 :class:`ZipFile` instance or ``file`` suitable for passing to
540 the :class:`ZipFile` constructor).
541
542 ``at`` specifies the location of this Path within the zipfile,
543 e.g. 'dir/file.txt', 'dir/', or ''. Defaults to the empty string,
544 indicating the root.
545
546 .. note::
547 The :class:`Path` class does not sanitize filenames within the ZIP archive. Unlike
548 the :meth:`ZipFile.extract` and :meth:`ZipFile.extractall` methods, it is the
549 caller's responsibility to validate or sanitize filenames to prevent path traversal
550 vulnerabilities (for example, absolute paths or paths with ".." components). When handling
551 untrusted archives, consider resolving filenames using :func:`os.path.abspath`
552 and checking against the target directory with :func:`os.path.commonpath`.
553
554 Path objects expose the following features of :mod:`pathlib.Path`
555 objects:
556
557 Path objects are traversable using the ``/`` operator or ``joinpath``.
558
559 .. attribute:: Path.name
560
561 The final path component.
562
563 .. method:: Path.open(mode='r', *, pwd, **)
564
565 Invoke :meth:`ZipFile.open` on the current path.
566 Allows opening for read or write, text or binary
567 through supported modes: 'r', 'w', 'rb', 'wb'.
568 Positional and keyword arguments are passed through to
569 :class:`io.TextIOWrapper` when opened as text and
570 ignored otherwise.
571 ``pwd`` is the ``pwd`` parameter to
572 :meth:`ZipFile.open`.
573
574 .. versionchanged:: 3.9
575 Added support for text and binary modes for open. Default
576 mode is now text.
577
578 .. versionchanged:: 3.11.2
579 The ``encoding`` parameter can be supplied as a positional argument
580 without causing a :exc:`TypeError`. As it could in 3.9. Code needing to
581 be compatible with unpatched 3.10 and 3.11 versions must pass all
582 :class:`io.TextIOWrapper` arguments, ``encoding`` included, as keywords.
583
584 .. method:: Path.iterdir()
585
586 Enumerate the children of the current directory.
587
588 .. method:: Path.is_dir()
589
590 Return ``True`` if the current context references a directory.
591
592 .. method:: Path.is_file()
593
594 Return ``True`` if the current context references a file.
595
596 .. method:: Path.is_symlink()
597
598 Return ``True`` if the current context references a symbolic link.
599
600 .. versionadded:: 3.12
601
602 .. versionchanged:: 3.13
603 Previously, ``is_symlink`` would unconditionally return ``False``.
604
605 .. method:: Path.exists()
606
607 Return ``True`` if the current context references a file or
608 directory in the zip file.
609
610 .. data:: Path.suffix
611
612 The last dot-separated portion of the final component, if any.
613 This is commonly called the file extension.
614
615 .. versionadded:: 3.11
616 Added :data:`Path.suffix` property.
617
618 .. data:: Path.stem
619
620 The final path component, without its suffix.
621
622 .. versionadded:: 3.11
623 Added :data:`Path.stem` property.
624
625 .. data:: Path.suffixes
626
627 A list of the path’s suffixes, commonly called file extensions.
628
629 .. versionadded:: 3.11
630 Added :data:`Path.suffixes` property.
631
632 .. method:: Path.read_text(*, **)
633
634 Read the current file as unicode text. Positional and
635 keyword arguments are passed through to
636 :class:`io.TextIOWrapper` (except ``buffer``, which is
637 implied by the context).
638
639 .. versionchanged:: 3.11.2
640 The ``encoding`` parameter can be supplied as a positional argument
641 without causing a :exc:`TypeError`. As it could in 3.9. Code needing to
642 be compatible with unpatched 3.10 and 3.11 versions must pass all
643 :class:`io.TextIOWrapper` arguments, ``encoding`` included, as keywords.
644
645 .. method:: Path.read_bytes()
646
647 Read the current file as bytes.
648
649 .. method:: Path.joinpath(*other)
650
651 Return a new Path object with each of the *other* arguments
652 joined. The following are equivalent::
653
654 >>> Path(...).joinpath('child').joinpath('grandchild')
655 >>> Path(...).joinpath('child', 'grandchild')
656 >>> Path(...) / 'child' / 'grandchild'
657
658 .. versionchanged:: 3.10
659 Prior to 3.10, ``joinpath`` was undocumented and accepted
660 exactly one parameter.
661
662 The :pypi:`zipp` project provides backports
663 of the latest path object functionality to older Pythons. Use
664 ``zipp.Path`` in place of ``zipfile.Path`` for early access to
665 changes.
666
667 .. _pyzipfile-objects:
668
669 PyZipFile objects
670 -----------------
671
672 The :class:`PyZipFile` constructor takes the same parameters as the
673 :class:`ZipFile` constructor, and one additional parameter, *optimize*.
674
675 .. class:: PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, \
676 optimize=-1)
677
678 .. versionchanged:: 3.2
679 Added the *optimize* parameter.
680
681 .. versionchanged:: 3.4
682 ZIP64 extensions are enabled by default.
683
684 Instances have one method in addition to those of :class:`ZipFile` objects:
685
686 .. method:: PyZipFile.writepy(pathname, basename='', filterfunc=None)
687
688 Search for files :file:`\*.py` and add the corresponding file to the
689 archive.
690
691 If the *optimize* parameter to :class:`PyZipFile` was not given or ``-1``,
692 the corresponding file is a :file:`\*.pyc` file, compiling if necessary.
693
694 If the *optimize* parameter to :class:`PyZipFile` was ``0``, ``1`` or
695 ``2``, only files with that optimization level (see :func:`compile`) are
696 added to the archive, compiling if necessary.
697
698 If *pathname* is a file, the filename must end with :file:`.py`, and
699 just the (corresponding :file:`\*.pyc`) file is added at the top level
700 (no path information). If *pathname* is a file that does not end with
701 :file:`.py`, a :exc:`RuntimeError` will be raised. If it is a directory,
702 and the directory is not a package directory, then all the files
703 :file:`\*.pyc` are added at the top level. If the directory is a
704 package directory, then all :file:`\*.pyc` are added under the package
705 name as a file path, and if any subdirectories are package directories,
706 all of these are added recursively in sorted order.
707
708 *basename* is intended for internal use only.
709
710 *filterfunc*, if given, must be a function taking a single string
711 argument. It will be passed each path (including each individual full
712 file path) before it is added to the archive. If *filterfunc* returns a
713 false value, the path will not be added, and if it is a directory its
714 contents will be ignored. For example, if our test files are all either
715 in ``test`` directories or start with the string ``test_``, we can use a
716 *filterfunc* to exclude them::
717
718 >>> zf = PyZipFile('myprog.zip')
719 >>> def notests(s):
720 ... fn = os.path.basename(s)
721 ... return (not (fn == 'test' or fn.startswith('test_')))
722 ...
723 >>> zf.writepy('myprog', filterfunc=notests)
724
725 The :meth:`writepy` method makes archives with file names like
726 this::
727
728 string.pyc # Top level name
729 test/__init__.pyc # Package directory
730 test/testall.pyc # Module test.testall
731 test/bogus/__init__.pyc # Subpackage directory
732 test/bogus/myfile.pyc # Submodule test.bogus.myfile
733
734 .. versionchanged:: 3.4
735 Added the *filterfunc* parameter.
736
737 .. versionchanged:: 3.6.2
738 The *pathname* parameter accepts a :term:`path-like object`.
739
740 .. versionchanged:: 3.7
741 Recursion sorts directory entries.
742
743
744 .. _zipinfo-objects:
745
746 ZipInfo objects
747 ---------------
748
749 Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
750 :meth:`.infolist` methods of :class:`ZipFile` objects. Each object stores
751 information about a single member of the ZIP archive.
752
753 There is one classmethod to make a :class:`ZipInfo` instance for a filesystem
754 file:
755
756 .. classmethod:: ZipInfo.from_file(filename, arcname=None, *, \
757 strict_timestamps=True)
758
759 Construct a :class:`ZipInfo` instance for a file on the filesystem, in
760 preparation for adding it to a zip file.
761
762 *filename* should be the path to a file or directory on the filesystem.
763
764 If *arcname* is specified, it is used as the name within the archive.
765 If *arcname* is not specified, the name will be the same as *filename*, but
766 with any drive letter and leading path separators removed.
767
768 The *strict_timestamps* argument, when set to ``False``, allows to
769 zip files older than 1980-01-01 at the cost of setting the
770 timestamp to 1980-01-01.
771 Similar behavior occurs with files newer than 2107-12-31,
772 the timestamp is also set to the limit.
773
774 .. versionadded:: 3.6
775
776 .. versionchanged:: 3.6.2
777 The *filename* parameter accepts a :term:`path-like object`.
778
779 .. versionchanged:: 3.8
780 Added the *strict_timestamps* keyword-only parameter.
781
782
783 Instances have the following methods and attributes:
784
785 .. method:: ZipInfo.is_dir()
786
787 Return ``True`` if this archive member is a directory.
788
789 This uses the entry's name: directories should always end with ``/``.
790
791 .. versionadded:: 3.6
792
793
794 .. attribute:: ZipInfo.filename
795
796 Name of the file in the archive.
797
798
799 .. attribute:: ZipInfo.date_time
800
801 The time and date of the last modification to the archive member. This is a
802 tuple of six values representing the "last [modified] file time" and "last [modified] file date"
803 fields from the ZIP file's central directory.
804
805 The tuple contains:
806
807 +-------+--------------------------+
808 | Index | Value |
809 +=======+==========================+
810 | ``0`` | Year (>= 1980) |
811 +-------+--------------------------+
812 | ``1`` | Month (one-based) |
813 +-------+--------------------------+
814 | ``2`` | Day of month (one-based) |
815 +-------+--------------------------+
816 | ``3`` | Hours (zero-based) |
817 +-------+--------------------------+
818 | ``4`` | Minutes (zero-based) |
819 +-------+--------------------------+
820 | ``5`` | Seconds (zero-based) |
821 +-------+--------------------------+
822
823 .. note::
824
825 The ZIP format supports multiple timestamp fields in different locations
826 (central directory, extra fields for NTFS/UNIX systems, etc.). This attribute
827 specifically returns the timestamp from the central directory. The central
828 directory timestamp format in ZIP files does not support timestamps before
829 1980. While some extra field formats (such as UNIX timestamps) can represent
830 earlier dates, this attribute only returns the central directory timestamp.
831
832 The central directory timestamp is interpreted as representing local
833 time, rather than UTC time, to match the behavior of other zip tools.
834
835
836 .. attribute:: ZipInfo.compress_type
837
838 Type of compression for the archive member.
839
840
841 .. attribute:: ZipInfo.comment
842
843 Comment for the individual archive member as a :class:`bytes` object.
844
845
846 .. attribute:: ZipInfo.extra
847
848 Expansion field data. The `PKZIP Application Note`_ contains
849 some comments on the internal structure of the data contained in this
850 :class:`bytes` object.
851
852
853 .. attribute:: ZipInfo.create_system
854
855 System which created ZIP archive.
856
857
858 .. attribute:: ZipInfo.create_version
859
860 PKZIP version which created ZIP archive.
861
862
863 .. attribute:: ZipInfo.extract_version
864
865 PKZIP version needed to extract archive.
866
867
868 .. attribute:: ZipInfo.reserved
869
870 Must be zero.
871
872
873 .. attribute:: ZipInfo.flag_bits
874
875 ZIP flag bits.
876
877
878 .. attribute:: ZipInfo.volume
879
880 Volume number of file header.
881
882
883 .. attribute:: ZipInfo.internal_attr
884
885 Internal attributes.
886
887
888 .. attribute:: ZipInfo.external_attr
889
890 External file attributes.
891
892
893 .. attribute:: ZipInfo.header_offset
894
895 Byte offset to the file header.
896
897
898 .. attribute:: ZipInfo.CRC
899
900 CRC-32 of the uncompressed file.
901
902
903 .. attribute:: ZipInfo.compress_size
904
905 Size of the compressed data.
906
907
908 .. attribute:: ZipInfo.file_size
909
910 Size of the uncompressed file.
911
912
913 .. _zipfile-commandline:
914 .. program:: zipfile
915
916 Command-line interface
917 ----------------------
918
919 The :mod:`zipfile` module provides a simple command-line interface to interact
920 with ZIP archives.
921
922 If you want to create a new ZIP archive, specify its name after the :option:`-c`
923 option and then list the filename(s) that should be included:
924
925 .. code-block:: shell-session
926
927 $ python -m zipfile -c monty.zip spam.txt eggs.txt
928
929 Passing a directory is also acceptable:
930
931 .. code-block:: shell-session
932
933 $ python -m zipfile -c monty.zip life-of-brian_1979/
934
935 If you want to extract a ZIP archive into the specified directory, use
936 the :option:`-e` option:
937
938 .. code-block:: shell-session
939
940 $ python -m zipfile -e monty.zip target-dir/
941
942 For a list of the files in a ZIP archive, use the :option:`-l` option:
943
944 .. code-block:: shell-session
945
946 $ python -m zipfile -l monty.zip
947
948
949 Command-line options
950 ~~~~~~~~~~~~~~~~~~~~
951
952 .. option:: -l <zipfile>
953 --list <zipfile>
954
955 List files in a zipfile.
956
957 .. option:: -c <zipfile> <source1> ... <sourceN>
958 --create <zipfile> <source1> ... <sourceN>
959
960 Create zipfile from source files.
961
962 .. option:: -e <zipfile> <output_dir>
963 --extract <zipfile> <output_dir>
964
965 Extract zipfile into target directory.
966
967 .. option:: -t <zipfile>
968 --test <zipfile>
969
970 Test whether the zipfile is valid or not.
971
972 .. option:: --metadata-encoding <encoding>
973
974 Specify encoding of member names for :option:`-l`, :option:`-e` and
975 :option:`-t`.
976
977 .. versionadded:: 3.11
978
979
980 Decompression pitfalls
981 ----------------------
982
983 The extraction in zipfile module might fail due to some pitfalls listed below.
984
985 From file itself
986 ~~~~~~~~~~~~~~~~
987
988 Decompression may fail due to incorrect password / CRC checksum / ZIP format or
989 unsupported compression method / decryption.
990
991 File system limitations
992 ~~~~~~~~~~~~~~~~~~~~~~~
993
994 Exceeding limitations on different file systems can cause decompression failed.
995 Such as allowable characters in the directory entries, length of the file name,
996 length of the pathname, size of a single file, and number of files, etc.
997
998 .. _zipfile-resources-limitations:
999
1000 Resources limitations
1001 ~~~~~~~~~~~~~~~~~~~~~
1002
1003 The lack of memory or disk volume would lead to decompression
1004 failed. For example, decompression bombs (aka `ZIP bomb`_)
1005 apply to zipfile library that can cause disk volume exhaustion.
1006
1007 Interruption
1008 ~~~~~~~~~~~~
1009
1010 Interruption during the decompression, such as pressing control-C or killing the
1011 decompression process may result in incomplete decompression of the archive.
1012
1013 Default behaviors of extraction
1014 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1015
1016 Not knowing the default extraction behaviors
1017 can cause unexpected decompression results.
1018 For example, when extracting the same archive twice,
1019 it overwrites files without asking.
1020
1021
1022 .. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb
1023 .. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT