Text of docs.python.org › uk › 3 › library › gzip.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

gzip — Support for gzip files — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Стиснення та архівування даних » gzip — Support for gzip files | Theme | gzip — Support for gzip files ¶ Вихідний код: Lib/gzip.py Цей модуль надає простий інтерфейс для стиснення та розпакування файлів, як це робили б програми GNU gzip і gunzip .

This is an optional module . If it is missing from your copy of CPython, look for documentation from your distributor (that is, whoever provided Python to you). If you are the distributor, see Requirements for optional modules . Стиснення даних забезпечується модулем zlib . The gzip module provides the GzipFile class, as well as the open() , compress() and decompress() convenience functions.

The GzipFile class reads and writes gzip -format files, automatically compressing or decompressing the data so that it looks like an ordinary file object . Зауважте, що додаткові формати файлів, які можна розпакувати програмами gzip і gunzip , наприклад ті, створені compress і pack , не підтримуються цим модуль. Модуль визначає такі елементи: gzip. open ( filename , mode = 'rb' , compresslevel = 6 , encoding = None , errors = None , newline = None ) ¶ Відкрийте файл, стиснутий gzip, у двійковому або текстовому режимі, повертаючи file object .

Аргументом filename може бути фактичне ім’я файлу (об’єкт str або bytes ) або наявний файловий об’єкт для читання або запису. Аргумент mode може бути будь-яким із 'r' , 'rb' , 'a' , 'ab' , 'w' , 'wb' , 'x' або 'xb' для бінарного режиму або 'rt' , 'at' , 'wt' або 'xt'' для текстового режиму.

Типовим є 'rb' . Аргумент compresslevel є цілим числом від 0 до 9, як і для конструктора GzipFile . Для бінарного режиму ця функція еквівалентна конструктору GzipFile : GzipFile(filename, mode, compresslevel) . У цьому випадку аргументи encoding , errors і newline не повинні надаватися.

Для текстового режиму створюється об’єкт GzipFile , який загортається в екземпляр io.TextIOWrapper із вказаним кодуванням, поведінкою обробки помилок і закінченнями рядків. Змінено в версії 3.3: Додано підтримку того, що ім’я файлу є об’єктом файлу, підтримується текстовий режим, а також аргументи кодування , помилки та новий рядок .

Змінено в версії 3.4: Додано підтримку режимів 'x' , 'xb' і 'xt' . Змінено в версії 3.6: Приймає path-like object . Змінено в версії 3.15: The default compression level was reduced to 6 (down from 9). It is the default level used by most compression tools and a better tradeoff between speed and performance. 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 = 6 , 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 , у цьому випадку ім’я_файлу відкривається, щоб надати об’єкт файлу.

Якщо fileobj не є None , аргумент filename використовується лише для включення в заголовок файлу gzip , який може містити оригінальну назву нестисненого файлу. За замовчуванням ім’я файлу fileobj , якщо воно помітне; інакше за замовчуванням буде порожній рядок, і в цьому випадку оригінальна назва файлу не буде включена в заголовок.

Аргумент mode може бути будь-яким із 'r' , 'rb' , 'a' , 'ab' , 'w' , 'wb' , 'x' або 'xb' , залежно від того, чи буде файл читатися чи записуватися. Типовим є режим fileobj , якщо він помітний; інакше за замовчуванням буде 'rb' . У майбутніх випусках Python режим fileobj не використовуватиметься.

Краще завжди вказувати режим для запису. Зауважте, що файл завжди відкривається у двійковому режимі. Щоб відкрити стислий файл у текстовому режимі, використовуйте open() (або загорніть свій GzipFile у io.TextIOWrapper ). The compresslevel argument is an integer from 0 to 9 controlling the level of compression; 1 is fastest and produces the least compression, and 9 is slowest and produces the most compression.

0 is no compression. The default is 6 . 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. Set mtime to 0 to generate a compressed stream that does not depend on creation time. If mtime is omitted or None , the current time is used; however, if the current time is outside the range 00:00:00 UTC, January 1, 1970 through 06:28:15 UTC, February 7, 2106, or explicitly passed mtime argument is outside the range 0 to 2**32-1 , then the value 0 is used instead.

See below for the mtime attribute that is set when decompressing. 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 ) ¶ Read n uncompressed bytes without advancing the file position. The number of bytes returned may be more or less than requested. Примітка Хоча виклик peek() не змінює позицію файлу GzipFile , він може змінити позицію основного файлового об’єкта (наприклад, якщо GzipFile було створено за допомогою fileobj параметр).

Added in version 3.2. mode ¶ 'rb' for reading and 'wb' for writing. Змінено в версії 3.13: In previous versions it was an integer 1 or 2 . mtime ¶ When decompressing, this attribute is set to the last timestamp in the most recently read head

The rest of this page is on the live site.