gzip --- Support for gzip files

ソースコード: Lib/gzip.py


このモジュールは、GNU の gzipgunzip のようにファイルを圧縮、展開するシンプルなインターフェイスを提供しています。

データ圧縮は zlib モジュールで提供されています。

gzipGzipFile クラスと、簡易関数 open()compress()、および decompress() を提供しています。GzipFile クラスは通常の ファイルオブジェクト と同様に gzip 形式のファイルを読み書きし、データを自動的に圧縮または展開します。

compresspack 等によって作成され、gzipgunzip が展開できる他のファイル形式についてはこのモジュールは対応していないので注意してください。

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

gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)

gzip 圧縮ファイルをバイナリまたはテキストモードで開き、ファイルオブジェクト を返します。

引数 filename には実際のファイル名 (str または bytes オブジェクト) か、既存のファイルオブジェクトを指定します。

引数 mode には、バイナリモード用に 'r''rb''a''ab''w''wb''x'、または 'xb'、テキストモード用に 'rt''at''wt'、または 'xt' を指定できます。デフォルトは 'rb' です。

引数 compresslevelGzipFile コンストラクタと同様に 0 から 9 の整数を取ります。

バイナリモードでは、この関数は GzipFile コンストラクタ GzipFile(filename, mode, compresslevel) と等価です。この時、引数 encodingerrors、および newline を指定してはいけません。

テキストモードでは、GzipFile オブジェクトが作成され、指定されたエンコーディング、エラーハンドラの挙動、および改行文字で io.TextIOWrapper インスタンスにラップされます。

バージョン 3.3 で変更: filename にファイルオブジェクト指定のサポート、テキストモードのサポート、および引数に encodingerrors、および newline を追加しました。

バージョン 3.4 で変更: Added support for the 'x', 'xb' and 'xt' modes.

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

exception gzip.BadGzipFile

An exception raised for invalid gzip files. It inherits from OSError. EOFError and zlib.error can also be raised for invalid gzip files.

Added in version 3.8.

class gzip.GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None, mtime=None)

Constructor for the GzipFile class, which simulates most of the methods of a file object, with the exception of the truncate() method. At least one of fileobj and filename must be given a non-trivial value.

クラスの新しいインスタンスは、 fileobj に基づいて作成されます。 fileobj は通常のファイル、 io.BytesIO オブジェクト、 そしてその他ファイルをシミュレートできるオブジェクトでかまいません。 値はデフォルトでは None で、その場合ファイルオブジェクトを生成するために filename を開きます。

fileobjNone でない場合、filename 引数は gzip ファイルヘッダにインクルードされることのみに使用されます。gzip ファイルヘッダは圧縮されていないファイルの元の名前をインクルードするかもしれません。認識可能な場合、規定値は fileobj のファイル名です。そうでない場合、規定値は空の文字列で、元のファイル名はヘッダにはインクルードされません。

The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', or 'xb', depending on whether the file will be read or written. The default is the mode of fileobj if discernible; otherwise, the default is 'rb'. In future Python releases the mode of fileobj will not be used. It is better to always specify mode for writing.

ファイルは常にバイナリモードで開かれることに注意してください。圧縮ファイルをテキストモードで開く場合、open() (または GzipFileio.TextIOWrapper でラップしたオブジェクト) を使ってください。

引数 compresslevel0 から 9 の整数を取り、圧縮レベルを制御します; 1 は最も高速で最小限の圧縮を行い、9 は最も低速ですが最大限の圧縮を行います。0 は圧縮しません。デフォルトは 9 です。

The mtime argument is an optional numeric timestamp to be written to the last modification time field in the stream when compressing. It should only be provided in compression mode. If omitted or None, the current time is used. See the mtime attribute for more details.

Calling a GzipFile object's close() method does not close fileobj, since you might wish to append more material after the compressed data. This also allows you to pass an io.BytesIO object opened for writing as fileobj, and retrieve the resulting memory buffer using the io.BytesIO object's getvalue() method.

GzipFile supports the io.BufferedIOBase interface, including iteration and the with statement. Only the truncate() method isn't implemented.

GzipFile は以下のメソッドと属性も提供しています:

peek(n)

ファイル内の位置を移動せずに展開した n バイトを読み込みます。呼び出し要求を満たすために、圧縮ストリームに対して最大 1 回の単一読み込みが行われます。返されるバイト数はほぼ要求した値になります。

注釈

peek() の呼び出しでは GzipFile のファイル位置は変わりませんが、下層のファイルオブジェクトの位置が変わる惧れがあります。(e.g. GzipFilefileobj 引数で作成された場合)

Added in version 3.2.

mtime

When decompressing, the value of the last modification time field in the most recently read header may be read from this attribute, as an integer. The initial value before reading any headers is None.

All gzip compressed streams are required to contain this timestamp field. Some programs, such as gunzip, make use of the timestamp. The format is the same as the return value of time.time() and the st_mtime attribute of the object returned by os.stat().

name

The path to the gzip file on disk, as a str or bytes. Equivalent to the output of os.fspath() on the original input path, with no other normalization, resolution or expansion.

バージョン 3.1 で変更: with 文がサポートされました。mtime コンストラクタ引数と mtime 属性が追加されました。

バージョン 3.2 で変更: ゼロパディングされたファイルやシーク出来ないファイルがサポートされました。

バージョン 3.3 で変更: io.BufferedIOBase.read1() メソッドを実装しました。

バージョン 3.4 で変更: 'x' ならびに 'xb' モードがサポートされました。

バージョン 3.5 で変更: 任意の バイトライクオブジェクト の書き込みがサポートされました。 read() メソッドが None を引数として受け取るようになりました。

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

バージョン 3.12 で変更: Remove the filename attribute, use the name attribute instead.

バージョン 3.9 で非推奨: Opening GzipFile for writing without specifying the mode argument is deprecated.

gzip.compress(data, compresslevel=9, *, mtime=None)

Compress the data, returning a bytes object containing the compressed data. compresslevel and mtime have the same meaning as in the GzipFile constructor above. When mtime is set to 0, this function is equivalent to zlib.compress() with wbits set to 31. The zlib function is faster.

Added in version 3.2.

バージョン 3.8 で変更: Added the mtime parameter for reproducible output.

バージョン 3.11 で変更: Speed is improved by compressing all data at once instead of in a streamed fashion. Calls with mtime set to 0 are delegated to zlib.compress() for better speed.

gzip.decompress(data)

Decompress the data, returning a bytes object containing the uncompressed data. This function is capable of decompressing multi-member gzip data (multiple gzip blocks concatenated together). When the data is certain to contain only one member the zlib.decompress() function with wbits set to 31 is faster.

Added in version 3.2.

バージョン 3.11 で変更: Speed is improved by decompressing members at once in memory instead of in a streamed fashion.

使い方の例

圧縮されたファイルを読み込む例:

import gzip
with gzip.open('/home/joe/file.txt.gz', 'rb') as f:
    file_content = f.read()

GZIP 圧縮されたファイルを作成する例:

import gzip
content = b"Lots of content here"
with gzip.open('/home/joe/file.txt.gz', 'wb') as f:
    f.write(content)

既存のファイルを GZIP 圧縮する例:

import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
    with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

バイナリ文字列を GZIP 圧縮する例:

import gzip
s_in = b"Lots of content here"
s_out = gzip.compress(s_in)

参考

zlib モジュール

gzip ファイル形式のサポートを行うために必要な基本ライブラリモジュール。

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

gzip モジュールは、 ファイルを圧縮、展開するための簡単なコマンドラインインターフェースを提供しています。

Once executed the gzip module keeps the input file(s).

バージョン 3.8 で変更: Add a new command line interface with a usage. By default, when you will execute the CLI, the default compression level is 6.

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

file

If file is not specified, read from sys.stdin.

--fast

Indicates the fastest compression method (less compression).

--best

Indicates the slowest compression method (best compression).

-d, --decompress

Decompress the given file.

-h, --help

ヘルプメッセージを出力します