gzip --- gzip ファイルのサポート¶
ソースコード: Lib/gzip.py
このモジュールは、GNU の gzip や gunzip のようにファイルを圧縮、展開するシンプルなインターフェイスを提供しています。
データ圧縮は zlib モジュールで提供されています。
gzip は GzipFile クラスと、簡易関数 open()、compress()、および decompress() を提供しています。GzipFile クラスは通常の ファイルオブジェクト と同様に gzip 形式のファイルを読み書きし、データを自動的に圧縮または展開します。
compress や pack 等によって作成され、gzip や gunzip が展開できる他のファイル形式についてはこのモジュールは対応していないので注意してください。
このモジュールは以下の項目を定義しています:
- 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'です。引数 compresslevel は
GzipFileコンストラクタと同様に 0 から 9 の整数を取ります。バイナリモードでは、この関数は
GzipFileコンストラクタGzipFile(filename, mode, compresslevel)と等価です。この時、引数 encoding、errors、および newline を指定してはいけません。テキストモードでは、
GzipFileオブジェクトが作成され、指定されたエンコーディング、エラーハンドラの挙動、および改行文字でio.TextIOWrapperインスタンスにラップされます。バージョン 3.3 で変更: filename にファイルオブジェクト指定のサポート、テキストモードのサポート、および引数に encoding、errors、および 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.EOFErrorandzlib.errorcan 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
GzipFileclass, which simulates most of the methods of a file object, with the exception of thetruncate()method. At least one of fileobj and filename must be given a non-trivial value.クラスの新しいインスタンスは、 fileobj に基づいて作成されます。 fileobj は通常のファイル、
io.BytesIOオブジェクト、 そしてその他ファイルをシミュレートできるオブジェクトでかまいません。 値はデフォルトでは None で、その場合ファイルオブジェクトを生成するために filename を開きます。fileobj が
Noneでない場合、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()(またはGzipFileをio.TextIOWrapperでラップしたオブジェクト) を使ってください。引数 compresslevel は
0から9の整数を取り、圧縮レベルを制御します;1は最も高速で最小限の圧縮を行い、9は最も低速ですが最大限の圧縮を行います。0は圧縮しません。デフォルトは9です。The optional mtime argument is the timestamp requested by gzip. The time is in Unix format, i.e., seconds since 00:00:00 UTC, January 1, 1970. If mtime is omitted or
None, the current time is used. Use mtime = 0 to generate a compressed stream that does not depend on creation time.See below for the
mtimeattribute that is set when decompressing.Calling a
GzipFileobject'sclose()method does not close fileobj, since you might wish to append more material after the compressed data. This also allows you to pass anio.BytesIOobject opened for writing as fileobj, and retrieve the resulting memory buffer using theio.BytesIOobject'sgetvalue()method.GzipFilesupports theio.BufferedIOBaseinterface, including iteration and thewithstatement. Only thetruncate()method isn't implemented.GzipFileは以下のメソッドと属性も提供しています:- peek(n)¶
Read n uncompressed bytes without advancing the file position. The number of bytes returned may be more or less than requested.
注釈
peek()の呼び出しではGzipFileのファイル位置は変わりませんが、下層のファイルオブジェクトの位置が変わる惧れがあります。(e.g.GzipFileが fileobj 引数で作成された場合)Added in version 3.2.
- mode¶
'rb'は読み込み用、'wb'は書き込み用です。バージョン 3.13 で変更: In previous versions it was an integer
1or2.
- mtime¶
When decompressing, this attribute is set to the last timestamp in the most recently read header. It is an integer, holding the number of seconds since the Unix epoch (00:00:00 UTC, January 1, 1970). The initial value before reading any headers is
None.
- name¶
The path to the gzip file on disk, as a
strorbytes. Equivalent to the output ofos.fspath()on the original input path, with no other normalization, resolution or expansion.
バージョン 3.2 で変更: ゼロパディングされたファイルやシーク出来ないファイルがサポートされました。
バージョン 3.3 で変更:
io.BufferedIOBase.read1()メソッドを実装しました。バージョン 3.4 で変更:
'x'ならびに'xb'モードがサポートされました。バージョン 3.5 で変更: 任意の バイトライクオブジェクト の書き込みがサポートされました。
read()メソッドがNoneを引数として受け取るようになりました。バージョン 3.6 で変更: path-like object を受け入れるようになりました。
バージョン 3.9 で非推奨: Opening
GzipFilefor writing without specifying the mode argument is deprecated.バージョン 3.12 で変更: Remove the
filenameattribute, use thenameattribute instead.
- gzip.compress(data, compresslevel=9, *, mtime=0)¶
Compress the data, returning a
bytesobject containing the compressed data. compresslevel and mtime have the same meaning as in theGzipFileconstructor above, but mtime defaults to 0 for reproducible output.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
0are delegated tozlib.compress()for better speed. In this situation the output may contain a gzip header "OS" byte value other than 255 "unknown" as supplied by the underlying zlib implementation.バージョン 3.13 で変更: The gzip header OS byte is guaranteed to be set to 255 when this function is used as was the case in 3.10 and earlier.
バージョン 3.14 で変更: The mtime parameter now defaults to 0 for reproducible output. For the previous behaviour of using the current time, pass
Noneto mtime.
- gzip.decompress(data)¶
Decompress the data, returning a
bytesobject 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 thezlib.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 ファイル形式のサポートを行うために必要な基本ライブラリモジュール。
In case gzip (de)compression is a bottleneck, the python-isal package speeds up (de)compression with a mostly compatible API.
コマンドラインインターフェイス¶
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.
コマンドラインオプション¶
- --fast¶
Indicates the fastest compression method (less compression).
- --best¶
Indicates the slowest compression method (best compression).
- -d, --decompress¶
Decompress the given file.
- -h, --help¶
ヘルプメッセージを出力します