gzipgzip 파일 지원

소스 코드: Lib/gzip.py


이 모듈은 GNU 프로그램 gzipgunzip처럼 파일을 압축하고 압축을 푸는 간단한 인터페이스를 제공합니다.

데이터 압축은 zlib 모듈에 의해 제공됩니다.

gzip 모듈은 open(), compress()decompress() 편리 함수뿐만 아니라 GzipFile 클래스도 제공합니다. 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'입니다.

compresslevel 인자는 GzipFile 생성자와 마찬가지로 0에서 9 사이의 정수입니다.

바이너리 모드의 경우, 이 함수는 GzipFile 생성자 GzipFile(filename, mode, compresslevel)와 동등합니다. 이 경우, encoding, errorsnewline 인자를 제공하면 안 됩니다.

텍스트 모드의 경우, GzipFile 객체가 만들어지고, 지정된 인코딩, 에러 처리 동작 및 줄 종료를 갖는 io.TextIOWrapper 인스턴스로 감싸집니다.

버전 3.3에서 변경: 파일 객체인 filename 지원, 텍스트 모드 지원 및 encoding, errorsnewline 인자가 추가되었습니다.

버전 3.4에서 변경: 'x', 'xb''xt' 모드에 대한 지원이 추가되었습니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

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.

버전 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를 기반으로 하는데, 일반 파일, io.BytesIO 객체 또는 파일을 흉내 내는 다른 객체가 될 수 있습니다. 기본값은 None이며, 이 경우 파일 객체를 제공하기 위해 filename이 열립니다.

fileobjNone이 아닐 때, filename 인자는 gzip 파일 헤더에 포함되는 데만 사용되며, 이 헤더에는 압축되지 않은 파일의 원래 파일명이 포함될 수 있습니다. 보고 알 수 있다면, fileobj의 파일명을 기본값으로 사용합니다; 그렇지 않으면, 기본값은 빈 문자열이며, 이 경우 원래 파일명은 헤더에 포함되지 않습니다.

mode 인자는 파일을 읽을지 쓸지에 따라 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' 또는 'xb' 중 하나일 수 있습니다. 보고 알 수 있다면, 기본값은 fileobj의 모드입니다; 그렇지 않으면, 기본값은 'rb'입니다. 향후 파이썬 릴리스에서는 fileobj의 모드가 사용되지 않습니다. 항상 쓰기를 위해서는 mode를 지정하는 것이 좋습니다.

파일이 항상 바이너리 모드로 열림에 유의하십시오. 텍스트 모드로 압축 파일을 열려면, open()을 사용하십시오 (또는 GzipFileio.TextIOWrapper로 감싸십시오).

compresslevel 인자는 압축 수준을 제어하는 0에서 9까지의 정수입니다; 1은 가장 빠르고 압축률이 가장 낮으며, 9는 가장 느리고 압축률이 가장 높습니다. 0은 압축하지 않습니다. 기본값은 9입니다.

mtime 인자는 압축할 때 스트림의 마지막 수정 시간 필드에 기록되는 선택적 숫자 타임스탬프입니다. 압축 모드에서만 제공해야 합니다. 생략되거나 None이면, 현재 시각이 사용됩니다. 자세한 내용은 mtime 어트리뷰트를 참조하십시오.

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 바이트를 읽습니다. 호출을 만족시키기 위해 압축된 스트림에 대해 최대 한 번의 읽기가 수행됩니다. 반환된 바이트 수는 요청한 것보다 많거나 적을 수 있습니다.

참고

peek()를 호출할 때 GzipFile의 파일 위치가 변경되지는 않지만, 하부 파일 객체의 위치는 변경될 수 있습니다 (예를 들어, GzipFilefileobj 매개 변수로 생성된 경우).

버전 3.2에 추가.

mtime

압축을 풀 때, 가장 최근에 읽은 헤더의 마지막 수정 시간 필드의 값을 이 어트리뷰트에서 정수로 읽을 수 있습니다. 헤더를 읽기 전의 초깃값은 None입니다.

모든 gzip 압축 스트림에는 이 타임스탬프 필드가 있어야 합니다. gunzip과 같은 일부 프로그램은 타임스탬프를 사용합니다. 형식은 time.time()의 반환 값과 os.stat()에 의해 반환된 객체의 st_mtime 어트리뷰트와 같습니다.

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에서 변경: mtime 생성자 인자와 mtime 어트리뷰트와 함께 with 문에 대한 지원이 추가되었습니다.

버전 3.2에서 변경: 제로 패딩(zero-padded)된 파일과 위치 변경할 수 없는(unseekable) 파일에 대한 지원이 추가되었습니다.

버전 3.3에서 변경: io.BufferedIOBase.read1() 메서드가 이제 구현됩니다.

버전 3.4에서 변경: 'x''xb' 모드에 대한 지원이 추가되었습니다.

버전 3.5에서 변경: 임의의 바이트열류 객체를 쓰는 지원이 추가되었습니다. 이제 read() 메서드는 None 인자를 받아들입니다.

버전 3.6에서 변경: 경로류 객체를 받아들입니다.

버전 3.12에서 변경: Remove the filename attribute, use the name attribute instead.

버전 3.9부터 폐지됨: mode 인자를 지정하지 않고 쓰기 위해 GzipFile을 여는 것은 폐지되었습니다.

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.

버전 3.2에 추가.

버전 3.8에서 변경: 재현성 있는 출력을 위한 mtime 매개 변수가 추가되었습니다.

버전 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.

버전 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 모듈은 파일을 압축하거나 압축 해제하는 간단한 명령 줄 인터페이스를 제공합니다.

일단 실행되면 gzip 모듈은 입력 파일을 유지합니다.

버전 3.8에서 변경: 새로운 명령 중 인터페이스를 사용법과 함께 추가합니다. 기본적으로, CLI를 실행할 때, 기본 압축 수준은 6입니다.

명령 줄 옵션

file

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

--fast

가장 빠른 압축 방법(압축을 덜 함)을 나타냅니다.

--best

가장 느린 압축 방법(최상의 압축)을 나타냅니다.

-d, --decompress

주어진 파일의 압축을 풉니다.

-h, --help

도움말 메시지를 표시합니다.