Python gzip read file

Модуль gzip в Python

Модуль gzip Python обеспечивает очень простой способ сжатия и распаковки файлов и работает аналогично программам GNU gzip и gunzip.

В этом уроке мы изучим, какие классы присутствуют в этом модуле, который позволяет нам выполнять упомянутые операции вместе с дополнительными функциями, которые он предоставляет.

Этот модуль предоставляет нам класс Gzip, который содержит некоторые удобные функции, такие как open(), compress() и decopress().

Преимущество класса Gzip заключается в том, что он читает и записывает файлы gzip и автоматически сжимает и распаковывает их, так что в программе они выглядят так же, как обычные объекты File.

Важно помнить, что другие форматы, поддерживаемые программами gzip и gunzip, не поддерживаются этим модулем.

Использование модуля

Теперь мы начнем использовать упомянутые функции для выполнения операций сжатия и распаковки.

Запись сжатых файлов с помощью open()

Мы начнем с функции open(), которая создает экземпляр GzipFile и открывает файл в режиме wb для записи в сжатый файл:

import gzip import io import os output_file_name = 'jd_example.txt.gz' file_mode = 'wb' with gzip.open(output_file_name, file_mode) as output: with io.TextIOWrapper(output, encoding='utf-8') as encode: encode.write('We can write anything in the file here.\n') print(output_file_name, 'contains', os.stat(output_file_name).st_size, 'bytes') os.system('file -b --mime <>'.format(output_file_name))

Посмотрим на результат этой программы:

Читайте также:  PHP: Behind the Parser

Функция gzip в python

Чтобы записать в сжатый файл, мы сначала открыли его в режиме wb и обернули экземпляр GzipFile с помощью TextIOWrapper из модуля io для кодирования текста Unicode в байты, которые подходят для сжатия.

Запись нескольких строк в сжатый файл

На этот раз мы будем использовать почти тот же сценарий, что и выше, но напишем в него несколько строк. Давайте посмотрим на код, как этого можно добиться:

import gzip import io import os import itertools output_file_name = 'jd_example.txt.gz' file_mode = 'wb' with gzip.open(output_file_name, file_mode) as output: with io.TextIOWrapper(output, encoding='utf-8') as enc: enc.writelines( itertools.repeat('JournalDev, same line again and again!.\n', 10) ) os.system('gzcat jd_example.txt.gz')

Посмотрим на результат этой программы:

gzip сжимает несколько файлов

Чтение сжатых данных

Теперь, когда мы закончили процесс записи файла, мы также можем читать данные из сжатого файла. Теперь мы будем использовать другой файловый режим – rb, режим чтения.

import gzip import io import os read_file_name = 'jd_example.txt.gz' file_mode = 'rb' with gzip.open(read_file_name, file_mode) as input_file: with io.TextIOWrapper(input_file, encoding='utf-8') as dec: print(dec.read())

Посмотрим на результат этой программы:

Открытие файла

Обратите внимание, что мы не сделали здесь ничего особенного с Gzip, кроме передачи ему другого файлового режима. Процесс чтения выполняется TextIOWrapper, который использует объект File, как объект, предоставляемый модулем gzip.

Чтение потоков

Еще одно большое преимущество модуля gzip заключается в том, что его можно использовать для обертывания других типов потоков, чтобы они могли также использовать сжатие. Это чрезвычайно полезно, когда вы хотите передавать большой объем данных через веб-сокеты.

Давайте посмотрим, как мы можем сжимать и распаковывать данные потока:

import gzip from io import BytesIO import binascii write_mode = 'wb' read_mode = 'rb' uncompressed = b'Reiterated line n times.\n' * 8 print('Uncompressed Data:', len(uncompressed)) print(uncompressed) buf = BytesIO() with gzip.GzipFile(mode=write_mode, fileobj=buf) as file: file.write(uncompressed) compressed = buf.getvalue() print('Compressed Data:', len(compressed)) print(binascii.hexlify(compressed)) inbuffer = BytesIO(compressed) with gzip.GzipFile(mode=read_mode, fileobj=inbuffer) as file: read_data = file.read(len(uncompressed)) print('\nReading it again:', len(read_data)) print(read_data)

Посмотрим на результат этой программы:

Чтение потока в python

Обратите внимание, что при записи нам не нужно было указывать параметры длины. Но этого не произошло, когда мы перечитали данные. Нам пришлось явно передать длину функции read().

Источник

How to Read a gzip File in Python?

gzip file format is one of the most common formats for compressing/decompressing files. gzip compression on text files greatly reduce the space used to store the text file. If you are working with a big data file, often the big text files is compressed with gzip or “gzipped” to save space. A naive way to work with compressed gzip file is to uncompress it and work with much bigger unzipped file line by line. Clearly, that is not the best solution.

In Python, you can directly work with gzip file. All you need is the Python library gzip.

How to read a gzip file line by line in Python?

with gzip.open('big_file.txt.gz', 'rb') as f: for line in f: print(line)

How to Create a gzip File in Python

We can also use gzip library to create gzip (compressed) file by dumping the whole text content you have

all_of_of_your_content = "all the content of a big text file" with gzip.open('file.txt.gz', 'wb') as f: f.write(all_of_your_content)

How to create gzip (compressed file) from an existing file?

We can create gzip file from plain txt file (unzipped) without reading line by line using shutil library. The shutil module offers high-level operations on files copying and deletion. We will first open the unzipped file, then open the zipped file and use shutil to copy the unzipped file object to zipped file object.

import shutil # open the unzipped file with flie handler inp_f with open("test_file.txt","rb") as inp_f: # open the output zipped file with file handler out_f with gzip.open("test_file.txt.gz","wb") as out_f: # use shutil to copy the file objec shutil.copyfileobj(inp_f,out_f)

Источник

13.2. gzip — Support for gzip files¶

This module provides a simple interface to compress and decompress files just like the GNU programs gzip and gunzip would.

The data compression is provided by the zlib module.

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 .

Note that additional file formats which can be decompressed by the gzip and gunzip programs, such as those produced by compress and pack, are not supported by this module.

The module defines the following items:

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

Open a gzip-compressed file in binary or text mode, returning a file object .

The filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to.

The mode argument can be any of ‘r’ , ‘rb’ , ‘a’ , ‘ab’ , ‘w’ , ‘wb’ , ‘x’ or ‘xb’ for binary mode, or ‘rt’ , ‘at’ , ‘wt’ , or ‘xt’ for text mode. The default is ‘rb’ .

The compresslevel argument is an integer from 0 to 9, as for the GzipFile constructor.

For binary mode, this function is equivalent to the GzipFile constructor: GzipFile(filename, mode, compresslevel) . In this case, the encoding, errors and newline arguments must not be provided.

For text mode, a GzipFile object is created, and wrapped in an io.TextIOWrapper instance with the specified encoding, error handling behavior, and line ending(s).

Changed in version 3.3: Added support for filename being a file object, support for text mode, and the encoding, errors and newline arguments.

Changed in version 3.4: Added support for the ‘x’ , ‘xb’ and ‘xt’ modes.

Changed in version 3.6: Accepts a path-like object .

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.

The new class instance is based on fileobj, which can be a regular file, an io.BytesIO object, or any other object which simulates a file. It defaults to None , in which case filename is opened to provide a file object.

When fileobj is not None , the filename argument is only used to be included in the gzip file header, which may include the original filename of the uncompressed file. It defaults to the filename of fileobj, if discernible; otherwise, it defaults to the empty string, and in this case the original filename is not included in the header.

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’ .

Note that the file is always opened in binary mode. To open a compressed file in text mode, use open() (or wrap your GzipFile with an 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 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 also provides the following method and attribute:

Read n uncompressed bytes without advancing the file position. At most one single read on the compressed stream is done to satisfy the call. The number of bytes returned may be more or less than requested.

While calling peek() does not change the file position of the GzipFile , it may change the position of the underlying file object (e.g. if the GzipFile was constructed with the fileobj parameter).

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

Changed in version 3.1: Support for the with statement was added, along with the mtime constructor argument and mtime attribute.

Changed in version 3.2: Support for zero-padded and unseekable files was added.

Changed in version 3.3: The io.BufferedIOBase.read1() method is now implemented.

Changed in version 3.4: Added support for the ‘x’ and ‘xb’ modes.

Changed in version 3.5: Added support for writing arbitrary bytes-like objects . The read() method now accepts an argument of None .

Changed in version 3.6: Accepts a path-like object .

Compress the data, returning a bytes object containing the compressed data. compresslevel has the same meaning as in the GzipFile constructor above.

Decompress the data, returning a bytes object containing the uncompressed data.

13.2.1. Examples of usage¶

Example of how to read a compressed file:

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

Example of how to create a compressed GZIP file:

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

Example of how to GZIP compress an existing file:

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) 

Example of how to GZIP compress a binary string:

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

Module zlib The basic data compression module needed to support the gzip file format.

Источник

Оцените статью