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