13.5. "zipfile" --- ZIP アーカイブの処理
****************************************

**ソースコード:** 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.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 アーカイブプログラムおよびプログ
     ラム開発ライブラリに関する情報。


13.5.1. ZipFile オブジェクト
============================

class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True)

   Open a ZIP file, where *file* can be a path to a file (a string), a
   file-like object or a *path-like object*. The *mode* parameter
   should be "'r'" to read an existing file, "'w'" to truncate and
   write a new file, "'a'" to append to an existing file, or "'x'" to
   exclusively create and write a new file. If *mode* is "'x'" and
   *file* refers to an existing file, a "FileExistsError" will be
   raised. If *mode* is "'a'" and *file* refers to an existing ZIP
   file, then additional files are added to it.  If *file* does not
   refer to a ZIP file, then a new ZIP archive is appended to the
   file.  This is meant for adding a ZIP archive to another file (such
   as "python.exe").  If *mode* is "'a'" and the file does not exist
   at all, it is created. If *mode* is "'r'" or "'a'", the file should
   be seekable. *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.

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

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

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

   バージョン 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 で変更: The *file* parameter accepts a *path-like
   object*.

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.

   "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()", "__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 で変更: "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)

   メンバをアーカイブから現在の作業ディレクトリに展開します。*member*
   は展開するファイルのフルネームまたは "ZipInfo" オブジェクトでなけれ
   ばなりません。ファイル情報は可能な限り正確に展開されます。*path* は
   展開先のディレクトリを指定します。*member* はファイル名または
   "ZipInfo" オブジェクトです。*pwd* は暗号化ファイルに使われるパスワ
   ードです。

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

   注釈: メンバのファイル名が絶対パスなら、ドライブ/UNC sharepoint
     および 先頭の (バック) スラッシュは取り除かれます。例えば、Unix
     で "///foo/bar" は "foo/bar" となり、Window で "C:\foo\bar" は
     "foo\bar" となります。また、メンバのファイル名に含まれる全ての
     "".."" は取り除かれます。例えば、"../../foo../../ba..r" は
     "foo../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)

   すべてのメンバをアーカイブから現在の作業ディレクトリに展開します。
   *path* は展開先のディレクトリを指定します。*members* は、オプション
   で、"namelist()" で返されるリストの部分集合でなければなりません。
   *pwd* は、暗号化ファイルに使われるパスワードです。

   警告: 信頼できないソースからきた 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)

   *pwd* を展開する圧縮ファイルのデフォルトパスワードとして指定します
   。

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 and, if specified, it will override 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)

   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. The archive must be open with mode "'w'", "'x'" or
   "'a'".

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

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

   バージョン 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])

   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'".

   *compress_type* が指定された場合、その値はコンストラクタに与えられ
   た *compression* の値か、*zinfo_or_arcname* が "ZipInfo" のインスタ
   ンスだったときはその値をオーバーライドします。

   注釈: "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.filename

   Name of the ZIP file.

ZipFile.debug

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

ZipFile.comment

   The comment associated with the ZIP file as a "bytes" object. If
   assigning a comment to a "ZipFile" instance created with mode
   "'w'", "'x'" or "'a'", it should be no longer than 65535 bytes.
   Comments longer than this will be truncated.


13.5.2. PyZipFile オブジェクト
==============================

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

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

   バージョン 3.2 で追加: パラメータに *optimize* を追加しました。

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

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

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

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

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

      "PyZipFile" の *optimize* パラメータが "0"、"1"、あるいは "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.

      *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 で追加: *filterfunc* パラメータ。

      バージョン 3.6.2 で変更: The *pathname* parameter accepts a
      *path-like object*.


13.5.3. 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)

   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.

   バージョン 3.6 で追加.

   バージョン 3.6.2 で変更: The *filename* parameter accepts a *path-
   like object*.

Instances have the following methods and attributes:

ZipInfo.is_dir()

   Return "True" if this archive member is a directory.

   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

   Expansion field data.  The PKZIP Application Note contains some
   comments on the internal structure of the data contained in this
   "bytes" object.

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

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


13.5.4. コマンドラインインターフェイス
======================================

"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


13.5.4.1. コマンドラインオプション
----------------------------------

-l <zipfile>

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

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

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

-e <zipfile> <output_dir>

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

-t <zipfile>

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