zipfile --- ZIP アーカイブの処理

Source code: Lib/zipfile.py


ZIP は一般によく知られているアーカイブ (書庫化) および圧縮の標準ファイルフォーマットです。このモジュールでは ZIP 形式のファイルの作成、読み書き、追記、書庫内のファイル一覧の作成を行うためのツールを提供します。より高度な使い方でこのモジュールを利用したいのであれば、 PKZIP Application Note に定義されている ZIP ファイルフォーマットの理解が必要になるでしょう。

このモジュールは現在マルチディスク ZIP ファイルを扱うことはできません。ZIP64 拡張を利用する ZIP ファイル (サイズが 4 GiB を超えるような ZIP ファイル) は扱えます。このモジュールは暗号化されたアーカイブの復号をサポートしますが、現在暗号化ファイルを作成することはできません。C 言語ではなく、Python で実装されているため、復号は非常に遅くなっています。

このモジュールは以下の項目を定義しています:

exception zipfile.BadZipFile

正常ではない ZIP ファイルに対して送出されるエラーです。

バージョン 3.2 で追加.

exception zipfile.BadZipfile

BadZipFile の別名です。過去のバージョンの Python との互換性のために用意されています。

バージョン 3.2 で非推奨.

exception zipfile.LargeZipFile

ZIP ファイルが ZIP64 の機能を必要としているが、その機能が有効化されていない場合に送出されるエラーです。

class zipfile.ZipFile

ZIP ファイルの読み書きのためのクラスです。コンストラクタの詳細については、ZipFile オブジェクト 節を参照してください。

class zipfile.Path

pathlib.Path インターフェースの一部を実装したクラスです。 importlib.resources.abc.Traversable インターフェースは完全に実装しています。

バージョン 3.8 で追加.

class zipfile.PyZipFile

Python ライブラリを含む、ZIP アーカイブを作成するためのクラスです。

class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))

アーカイブ内の 1 個のメンバの情報を取得するために使うクラスです。このクラスのインスタンスは ZipFile オブジェクトの getinfo() および infolist() メソッドによって返されます。ほとんどの zipfile モジュールの利用者はこのクラスのインスタンスを作成する必要はなく、このモジュールによって作成されたものを使用できます。filename はアーカイブメンバのフルネームでなければならず、date_time はファイルが最後に変更された日時を表す 6 個のフィールドのタプルでなければなりません; フィールドは ZipInfo オブジェクト 節で説明されています。

zipfile.is_zipfile(filename)

filename が正しいマジックナンバをもつ ZIP ファイルの時に True を返し、そうでない場合 False を返します。filename にはファイルやファイルライクオブジェクトを渡すこともできます。

バージョン 3.1 で変更: ファイルおよびファイルライクオブジェクトをサポートしました。

zipfile.ZIP_STORED

アーカイブメンバを圧縮しない (複数ファイルを一つにまとめるだけ) ことを表す数値定数です。

zipfile.ZIP_DEFLATED

通常の ZIP 圧縮方法を表す数値定数です。これには zlib モジュールが必要です。

zipfile.ZIP_BZIP2

BZIP2 圧縮方法を表す数値定数です。これには bz2 モジュールが必要です。

バージョン 3.3 で追加.

zipfile.ZIP_LZMA

LZMA 圧縮方法を表す数値定数です。これには lzma モジュールが必要です。

バージョン 3.3 で追加.

注釈

ZIP ファイルフォーマット仕様は 2001 年より bzip2 圧縮を、2006 年より LZMA 圧縮をサポートしていますが、(過去の Python リリースを含む) 一部のツールはこれら圧縮方式をサポートしていないため、ZIP ファイルの処理を全く受け付けないか、あるいは個々のファイルの抽出に失敗する場合があります。

参考

PKZIP Application Note

ZIP ファイルフォーマットおよびアルゴリズムを作成した Phil Katz によるドキュメント。

Info-ZIP Home Page

Info-ZIP プロジェクトによる ZIP アーカイブプログラムおよびプログラム開発ライブラリに関する情報。

ZipFile オブジェクト

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True, metadata_encoding=None)

ZIP ファイルを開きます。 file はファイルのパス (文字列) か、ファイルライクオブジェクト、 path-like object のいずれかです。

mode パラメータには、既存のファイルを読み込む場合は 'r' 、内容を消去して新しいファイルに書き込む場合は 'w' 、既存のファイルの末尾に追加する場合は 'a' 、ファイルが存在しない場合にのみファイルを作成して書き込む場合は 'x' を指定します。 mode'x'file が既存のファイルを指している場合、 FileExistsError が発生します。 mode'a'file が既存の ZIP ファイルを指している場合、新しい ZIP アーカイブがそのファイルに追加されます。 file が ZIP ファイルでない場合は、ファイルの末尾にあたらしい ZIP アーカイブが追加されます。 これは、既存のファイル (例えば python.exe) に ZIP アーカイブを付け加える用途を想定したものです。 mode'a'file が存在しない場合は、ファイルが作成されます。 mode'r''a' の場合、ファイルはシーク可能である必要があります。

compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED.

If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions.

The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information).

The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit.

When mode is 'r', metadata_encoding may be set to the name of a codec, which will be used to decode metadata such as the names of members and ZIP comments.

ファイルがモード 'w''x' または 'a' で作成され、その後そのアーカイブにファイルを追加することなく クローズ された場合、空のアーカイブのための適切な ZIP 構造がファイルに書き込まれます。

ZipFile はコンテキストマネージャにもなっているので、with 文をサポートしています。次の例では、myzipwith 文のブロックが終了したときに、(たとえ例外が発生したとしても) クローズされます:

with ZipFile('spam.zip', 'w') as myzip:
    myzip.write('eggs.txt')

注釈

metadata_encoding is an instance-wide setting for the ZipFile. It is not currently possible to set this on a per-member basis.

This attribute is a workaround for legacy implementations which produce archives with names in the current locale encoding or code page (mostly on Windows). According to the .ZIP standard, the encoding of metadata may be specified to be either IBM code page (default) or UTF-8 by a flag in the archive header. That flag takes precedence over metadata_encoding, which is a Python-specific extension.

バージョン 3.2 で変更: ZipFile をコンテキストマネージャとして使用できるようになりました。

バージョン 3.3 で変更: bzip2 および lzma 圧縮をサポートしました。

バージョン 3.4 で変更: ZIP64 拡張がデフォルトで有効になりました。

バージョン 3.5 で変更: seek 出来ないストリームのサポートが追加されました。'x' モードのサポートが追加されました。

バージョン 3.6 で変更: Previously, a plain RuntimeError was raised for unrecognized compression values.

バージョン 3.6.2 で変更: file 引数が path-like object を受け入れるようになりました。

バージョン 3.7 で変更: compresslevel パラメータが追加されました。

バージョン 3.8 で変更: The strict_timestamps keyword-only parameter.

バージョン 3.11 で変更: Added support for specifying member name encoding for reading metadata in the zipfile's directory and file headers.

ZipFile.close()

アーカイブファイルをクローズします。close() はプログラムを終了する前に必ず呼び出さなければなりません。さもないとアーカイブ上の重要なレコードが書き込まれません。

ZipFile.getinfo(name)

アーカイブメンバ name に関する情報を持つ ZipInfo オブジェクトを返します。アーカイブに含まれないファイル名に対して getinfo() を呼び出すと、KeyError が送出されます。

ZipFile.infolist()

アーカイブに含まれる各メンバの ZipInfo オブジェクトからなるリストを返します。既存のアーカイブファイルを開いている場合、リストの順番は実際の ZIP ファイル中のメンバの順番と同じになります。

ZipFile.namelist()

アーカイブメンバの名前のリストを返します。

ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)

Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. pwd is the password used to decrypt encrypted ZIP files as a bytes object.

open() はコンテキストマネージャでもあるので with 文をサポートしています:

with ZipFile('spam.zip') as myzip:
    with myzip.open('eggs.txt') as myfile:
        print(myfile.read())

With mode 'r' the file-like object (ZipExtFile) is read-only and provides the following methods: read(), readline(), readlines(), seek(), tell(), __iter__(), __next__(). These objects can operate independently of the ZipFile.

With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError.

When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter.

注釈

open()read()、および extract() メソッドには、ファイル名または ZipInfo オブジェクトを指定できます。これは重複する名前のメンバを含む ZIP ファイルを読み込むときにそのメリットを享受できるでしょう。

バージョン 3.6 で変更: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.

バージョン 3.6 で変更: ZipFile.open() can now be used to write files into the archive with the mode='w' option.

バージョン 3.6 で変更: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.extract(member, path=None, pwd=None)

Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files as a bytes object.

作成された (ディレクトリか新ファイルの) 正規化されたパスを返します。

注釈

メンバのファイル名が絶対パスなら、ドライブ/UNC sharepoint および先頭の (バック) スラッシュは取り除かれます。例えば、Unix で ///foo/barfoo/bar となり、Window で C:\foo\barfoo\bar となります。また、メンバのファイル名に含まれる全ての ".." は取り除かれます。例えば、../../foo../../ba..rfoo../ba..r となります。Windows では、不正な文字 (:, <, >, |, ", ?, および *) はアンダースコア (_) で置き換えられます。

バージョン 3.6 で変更: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

バージョン 3.6.2 で変更: path パラメタが path-like object を受け付けるようになりました。

ZipFile.extractall(path=None, members=None, pwd=None)

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files as a bytes object.

警告

信頼できないソースからきた Zip ファイルを、事前に中身をチェックせずに展開してはいけません。ファイルを path の外側に作成することができるからです。例えば、 "/" で始まる絶対パスを持ったメンバーや、 2 つのドット ".." を持つファイル名などの場合です。このモジュールはそれを避けようとします。 extract() の注釈を参照してください。

バージョン 3.6 で変更: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

バージョン 3.6.2 で変更: path パラメタが path-like object を受け付けるようになりました。

ZipFile.printdir()

アーカイブの内容の一覧を sys.stdout に出力します。

ZipFile.setpassword(pwd)

Set pwd (a bytes object) as default password to extract encrypted files.

ZipFile.read(name, pwd=None)

Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files as a bytes object and, if specified, overrides the default password set with setpassword(). Calling read() on a ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available.

バージョン 3.6 で変更: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.testzip()

Read all the files in the archive and check their CRC's and file headers. Return the name of the first bad file, or else return None.

バージョン 3.6 で変更: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)

Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. Similarly, compresslevel will override the constructor if given. The archive must be open with mode 'w', 'x' or 'a'.

注釈

The ZIP file standard historically did not specify a metadata encoding, but strongly recommended CP437 (the original IBM PC encoding) for interoperability. Recent versions allow use of UTF-8 (only). In this module, UTF-8 will automatically be used to write the member names if they contain any non-ASCII characters. It is not possible to write member names in any encoding other than ASCII or UTF-8.

注釈

アーカイブ名はアーカイブルートに対する相対パスでなければなりません。言い換えると、アーカイブ名はパスセパレータで始まってはいけません。

注釈

もし、arcname (arcname が与えられない場合は、filename) が null byte を含むなら、アーカイブ中のファイルのファイル名は、null byte までで切り詰められます。

注釈

A leading slash in the filename may lead to the archive being impossible to open in some zip programs on Windows systems.

バージョン 3.6 で変更: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)

Write a file into the archive. The contents is data, which may be either a str or a bytes instance; if it is a str, it is encoded as UTF-8 first. zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it's an instance, at least the filename, date, and time must be given. If it's a name, the date and time is set to the current date and time. The archive must be opened with mode 'w', 'x' or 'a'.

If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance). Similarly, compresslevel will override the constructor if given.

注釈

ZipInfo インスタンスを引数 zinfo_or_arcname として与えた場合、与えられた ZipInfo インスタンスのメンバーである compress_type で指定された圧縮方法が使われます。デフォルトでは、ZipInfo コンストラクターが、このメンバーを ZIP_STORED に設定します。

バージョン 3.2 で変更: 引数 compress_type を追加しました。

バージョン 3.6 で変更: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.

ZipFile.mkdir(zinfo_or_directory, mode=511)

Create a directory inside the archive. If zinfo_or_directory is a string, a directory is created inside the archive with the mode that is specified in the mode argument. If, however, zinfo_or_directory is a ZipInfo instance then the mode argument is ignored.

The archive must be opened with mode 'w', 'x' or 'a'.

バージョン 3.11 で追加.

以下のデータ属性も利用することができます:

ZipFile.filename

ZIP ファイルの名前です。

ZipFile.debug

使用するデバッグ出力レベルです。この属性は 0 (デフォルト、何も出力しない) から 3 (最も多く出力する) までの値に設定することができます。デバッグ情報は sys.stdout に出力されます。

ZipFile.comment

ZIP ファイルに bytes オブジェクトとして関連付けられたコメントです。モード 'w''x' または 'a' で作成された ZipFile インスタンスへコメントを割り当てる場合、文字列長は 65535 バイトまでにしてください。その長さを超えたコメントは切り捨てられます。

Path オブジェクト

class zipfile.Path(root, at='')

Construct a Path object from a root zipfile (which may be a ZipFile instance or file suitable for passing to the ZipFile constructor).

at specifies the location of this Path within the zipfile, e.g. 'dir/file.txt', 'dir/', or ''. Defaults to the empty string, indicating the root.

Path objects expose the following features of pathlib.Path objects:

Path objects are traversable using the / operator or joinpath.

Path.name

The final path component.

Path.open(mode='r', *, pwd, **)

Invoke ZipFile.open() on the current path. Allows opening for read or write, text or binary through supported modes: 'r', 'w', 'rb', 'wb'. Positional and keyword arguments are passed through to io.TextIOWrapper when opened as text and ignored otherwise. pwd is the pwd parameter to ZipFile.open().

バージョン 3.9 で変更: Added support for text and binary modes for open. Default mode is now text.

バージョン 3.11.2 で変更: The encoding parameter can be supplied as a positional argument without causing a TypeError. As it could in 3.9. Code needing to be compatible with unpatched 3.10 and 3.11 versions must pass all io.TextIOWrapper arguments, encoding included, as keywords.

Path.iterdir()

Enumerate the children of the current directory.

Path.is_dir()

Return True if the current context references a directory.

Path.is_file()

Return True if the current context references a file.

Path.exists()

Return True if the current context references a file or directory in the zip file.

Path.suffix

The file extension of the final component.

バージョン 3.11 で追加: Added Path.suffix property.

Path.stem

The final path component, without its suffix.

バージョン 3.11 で追加: Added Path.stem property.

Path.suffixes

A list of the path’s file extensions.

バージョン 3.11 で追加: Added Path.suffixes property.

Path.read_text(*, **)

Read the current file as unicode text. Positional and keyword arguments are passed through to io.TextIOWrapper (except buffer, which is implied by the context).

バージョン 3.11.2 で変更: The encoding parameter can be supplied as a positional argument without causing a TypeError. As it could in 3.9. Code needing to be compatible with unpatched 3.10 and 3.11 versions must pass all io.TextIOWrapper arguments, encoding included, as keywords.

Path.read_bytes()

Read the current file as bytes.

Path.joinpath(*other)

Return a new Path object with each of the other arguments joined. The following are equivalent:

>>> Path(...).joinpath('child').joinpath('grandchild')
>>> Path(...).joinpath('child', 'grandchild')
>>> Path(...) / 'child' / 'grandchild'

バージョン 3.10 で変更: Prior to 3.10, joinpath was undocumented and accepted exactly one parameter.

The zipp project provides backports of the latest path object functionality to older Pythons. Use zipp.Path in place of zipfile.Path for early access to changes.

PyZipFile オブジェクト

PyZipFile コンストラクタは ZipFile コンストラクタと同じパラメータに加え、optimize パラメータをとります。

class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)

バージョン 3.2 で変更: Added the optimize parameter.

バージョン 3.4 で変更: ZIP64 拡張がデフォルトで有効になりました。

インスタンスは ZipFile オブジェクトのメソッドの他に、追加のメソッドを 1 個持ちます:

writepy(pathname, basename='', filterfunc=None)

*.py ファイルを探し、一致するファイルをアーカイブに追加します。

PyZipFileoptimize 引数が与えられない場合、あるいは -1 が指定された場合、対応するファイルは *.pyc ファイルで、必要に応じてコンパイルします。

PyZipFileoptimize パラメータが 01、あるいは 2 の場合、それを最適化レベル (compile() 参照) とするファイルのみが、必要に応じてコンパイルされアーカイブに追加されます。

If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order.

basename は内部が使用するためだけのものです。

filterfunc を与える場合、単一の文字列引数を取る関数を渡してください。これには(個々のフルパスを含む)それぞれのパスがアーカイブに加えられる前に渡されます。 filterfunc が偽を返せば、そのパスはアーカイブに追加されず、ディレクトリだった場合はその中身が無視されます。例として、私たちのテストファイルが全て test ディレクトリの中にあるか、 test 文字列で始まるとしましょう。 filterfunc を使ってそれらを除外出来ます:

>>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
...     fn = os.path.basename(s)
...     return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)

writepy() メソッドは以下のようなファイル名でアーカイブを作成します:

string.pyc                   # Top level name
test/__init__.pyc            # Package directory
test/testall.pyc             # Module test.testall
test/bogus/__init__.pyc      # Subpackage directory
test/bogus/myfile.pyc        # Submodule test.bogus.myfile

バージョン 3.4 で変更: Added the filterfunc parameter.

バージョン 3.6.2 で変更: pathname 引数が path-like object を受け付けるようになりました。

バージョン 3.7 で変更: Recursion sorts directory entries.

ZipInfo オブジェクト

ZipInfo クラスのインスタンスは、ZipFile オブジェクトの getinfo() および infolist() メソッドによって返されます。各オブジェクトは ZIP アーカイブ内の 1 個のメンバに関する情報を格納します。

There is one classmethod to make a ZipInfo instance for a filesystem file:

classmethod ZipInfo.from_file(filename, arcname=None, *, strict_timestamps=True)

Construct a ZipInfo instance for a file on the filesystem, in preparation for adding it to a zip file.

filename should be the path to a file or directory on the filesystem.

If arcname is specified, it is used as the name within the archive. If arcname is not specified, the name will be the same as filename, but with any drive letter and leading path separators removed.

The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit.

バージョン 3.6 で追加.

バージョン 3.6.2 で変更: filename 引数が path-like object を受け入れるようになりました。

バージョン 3.8 で変更: Added the strict_timestamps keyword-only parameter.

インスタンスは以下のメソッドと属性を持ちます:

ZipInfo.is_dir()

アーカイブのメンバーがディレクトリの場合に True を返します。

This uses the entry's name: directories should always end with /.

バージョン 3.6 で追加.

ZipInfo.filename

アーカイブ中のファイル名。

ZipInfo.date_time

アーカイブメンバの最終更新日時。6 つの値からなるタプルになります:

インデックス

0

西暦年 (>= 1980)

1

月 (1 から始まる)

2

日 (1 から始まる)

3

時 (0 から始まる)

4

分 (0 から始まる)

5

秒 (0 から始まる)

注釈

ZIP ファイルフォーマットは 1980 年より前のタイムスタンプをサポートしていません。

ZipInfo.compress_type

アーカイブメンバの圧縮形式。

ZipInfo.comment

Comment for the individual archive member as a bytes object.

ZipInfo.extra

拡張フィールドデータ。この bytes オブジェクトに含まれているデータの内部構成については、PKZIP Application Note でコメントされています。

ZipInfo.create_system

ZIP アーカイブを作成したシステムを記述する文字列。

ZipInfo.create_version

このアーカイブを作成した PKZIP のバージョン。

ZipInfo.extract_version

このアーカイブを展開する際に必要な PKZIP のバージョン。

ZipInfo.reserved

予約領域。ゼロでなくてはなりません。

ZipInfo.flag_bits

ZIP フラグビット列。

ZipInfo.volume

ファイルヘッダのボリューム番号。

ZipInfo.internal_attr

内部属性。

ZipInfo.external_attr

外部ファイル属性。

ZipInfo.header_offset

ファイルヘッダへのバイトオフセット。

ZipInfo.CRC

圧縮前のファイルの CRC-32 チェックサム。

ZipInfo.compress_size

圧縮後のデータのサイズ。

ZipInfo.file_size

圧縮前のファイルのサイズ。

コマンドラインインターフェイス

zipfile モジュールは、 ZIP アーカイブを操作するための簡単なコマンドラインインターフェースを提供しています。

ZIP アーカイブを新規に作成したい場合、-c オプションの後にまとめたいファイルを列挙してください:

$ python -m zipfile -c monty.zip spam.txt eggs.txt

ディレクトリを渡すこともできます:

$ python -m zipfile -c monty.zip life-of-brian_1979/

ZIP アーカイブを特定のディレクトリに展開したい場合、-e オプションを使用してください:

$ python -m zipfile -e monty.zip target-dir/

ZIP アーカイブ内のファイル一覧を表示するには -l を使用してください:

$ python -m zipfile -l monty.zip

コマンドラインオプション

-l <zipfile>
--list <zipfile>

zipfile 内のファイル一覧を表示します。

-c <zipfile> <source1> ... <sourceN>
--create <zipfile> <source1> ... <sourceN>

ソースファイルから zipfile を作成します。

-e <zipfile> <output_dir>
--extract <zipfile> <output_dir>

zipfile を対象となるディレクトリに展開します。

-t <zipfile>
--test <zipfile>

zipfile が有効かどうか調べます。

--metadata-encoding <encoding>

Specify encoding of member names for -l, -e and -t.

バージョン 3.11 で追加.

Decompression pitfalls

The extraction in zipfile module might fail due to some pitfalls listed below.

From file itself

Decompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption.

File System limitations

Exceeding limitations on different file systems can cause decompression failed. Such as allowable characters in the directory entries, length of the file name, length of the pathname, size of a single file, and number of files, etc.

Resources limitations

The lack of memory or disk volume would lead to decompression failed. For example, decompression bombs (aka ZIP bomb) apply to zipfile library that can cause disk volume exhaustion.

Interruption

Interruption during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive.

Default behaviors of extraction

Not knowing the default extraction behaviors can cause unexpected decompression results. For example, when extracting the same archive twice, it overwrites files without asking.