Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','rt') as f:
    for line in f:
        print('got line', line)

Note: gzip.open(filename, mode) is an alias for gzip.GzipFile(filename, mode). I prefer the former, as it looks similar to with open(...) as f: used for opening uncompressed files.

Answer from fferri on Stack Overflow
🌐
Python
docs.python.org › 3 › library › gzip.html
gzip — Support for gzip files
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 ...
🌐
Quora
quora.com › How-do-you-read-a-gzip-file-without-unzipping
How to read a gzip file without unzipping - Quora
Answer (1 of 2): An odd idea, but i guess you might be looking for gunzip -l or simply just to open it in gui. But for actual file contents you can't do without extracting.
Top answer
1 of 6
6

You can use zcat to stream the uncompressed contents into grep or whatever filter you want, without incurring space overhead. E.g.

zcat bigfile.gz | grep PATTERN_I_NEED > much_smaller_sample

Also, if it's just grep you're streaming to, you can use zgrep e.g.

zgrep PATTERN_I_NEED bigfile.gz > much_smaller_sample

but zgrep doesn't support 100% of the features of grep on some systems.

2 of 6
5

Decompression takes place in chunks, and you don't need to hold all of the decompressed data in memory to get to a specific line.

You can combine the gzip module with the csv module and process the file row by row:

import gzip
import csv

with gzip.open('googlebooks-eng-all-3gram-20120701-th.gz', 'rb') as fobj:
    reader = csv.reader(fobj, delimiter='\t')
    for row in reader:
        print row

Now you can scan for the rows you want; as long as you don't try to store all rows in a list object but instead process them individually, you won't be using much memory at all.

Quick demo:

>>> import gzip
>>> import csv
>>> fobj = gzip.open('/tmp/googlebooks-eng-all-3gram-20120701-th.gz', 'rb')
>>> reader = csv.reader(fobj, delimiter='\t')
>>> print next(reader)
["T'Hooft , _NOUN_", '1937', '1', '1']

I used the next() function here to get just one row at a time from the reader but the principles are the same as using the reader in a loop.

The above uses very little memory; no more than a few kilobytes in file buffers and the current chunk to decompress, plus the Python strings in the row list.

🌐
Stack Overflow
stackoverflow.com › questions › 53391125 › how-to-read-multiple-gz-files-in-a-particular-directory-in-python-without-unzip
zip - how to read multiple .gz files in a particular directory in python without unzipping them - Stack Overflow
November 20, 2018 - import glob import gzip ZIPFILES='/var/tmp/Aakashdeep/aakashdeep_20181120*.gz' filelist = glob.glob(ZIPFILES) for gzfile in filelist: # print("#Starting " + gzfile) #if you want to know which file is being processed with gzip.open( gzfile, 'r') as f: for line in f: print(line)
🌐
Stack Overflow
stackoverflow.com › questions › 66743932 › send-gzip-data-without-unzipping
python - send gzip data without unzipping - Stack Overflow
list_of_files = glob.glob('/home/pi/src/git/RPI/DATA/*.gz') print(list_of_files) for file_data in list_of_files: zipp = gzip.GzipFile(file_data,'rb') file_content = zipp.read() #array = np.fromstring(file_content, dtype='f4') print(len(file_content)) #AT commands to send the file_content to FTP server
🌐
CmdLineTips
cmdlinetips.com › home › how to read a gzip file in python?
How to Read a gzip File in Python? - Python and R Tips
February 10, 2018 - ... We can also use gzip library ... We can create gzip file from plain txt file (unzipped) without reading line by line using shutil library....
Find elsewhere
🌐
Wsldp
elearning.wsldp.com › pcmagazine › read-gzip-file-without-extracting
How to Read Gzip File Without Extracting - e Learning
In Linux System we can read gzip files without extracting or uncompress. We can do this by using both command line and Graphical User Interface.
🌐
Python.org
discuss.python.org › python help
Get uncompressed file size without reading it? - Python Help - Discussions on Python.org
May 7, 2024 - I don’t suppose any of the various file compression modules can tell me the uncompressed file size without reading the file’s content? I’m sure anything like that would need to be supported by the underlying compression scheme, stashed somewhere in the file header or footer.
Top answer
1 of 4
11

You can't, because Gzip is not an archive format.

That's a bit of a crap explanation on its own, so let me break this down a bit more than I did in the comment...

Its just compression

Being "just a compression system" means that Gzip operates on input bytes (usually from a file) and outputs compressed bytes. You cannot know whether or not the bytes inside represent multiple files or just a single file -- it is just a stream of bytes that has been compressed. That is why you can accept gzipped data over a network, for example. Its bytes_in -> bytes_out.

What's a manifest?

A manifest is a header within an archive that acts as a table of contents for the archive. Note that now I am using the term "archive" and not "compressed stream of bytes". An archive implies that it is a collection of files or segments that are referred to by a manifest -- a compressed stream of bytes is just a stream of bytes.

What's inside a Gzip, anyway?

A somewhat simplified description of a .gz file's contents is:

  1. A header with a special number to indicate its a gzip, a version and a timestamp (10 bytes)
  2. Optional headers; usually including the original filename (if the compression target was a file)
  3. The body -- some compressed payload
  4. A CRC-32 checksum at the end (8 bytes)

That's it. No manifest.

Archive formats, on the other hand, will have a manifest inside. That's where the tar library would come in. Tar is just a way to shove a bunch of bits together into a single file, and places a manifest at the front that lets you know the names of the original files and what sizes they were before being concatenated into the archive. Hence, .tar.gz being so common.

There are utilities that allow you to decompress parts of a gzipped file at a time, or decompress it only in memory to then let you examine a manifest or whatever that may be inside. But the details of any manifest are specific to the archive format contained inside.

Note that this is different from a zip archive. Zip is an archive format, and as such contains a manifest. Gzip is a compression library, like bzip2 and friends.

2 of 4
4

As noted in the other answer, your question can only make sense if I take out the plural: "I have a .gz file and I need to get the name of file inside it using python."

A gzip header may or may not have a file name in it. The gzip utility will normally ignore the name in the header, and decompress to a file with the same name as the .gz file, but with the .gz stripped. E.g. your 1.gz would decompress to a file named 1, even if the header has the file name my_latest_data.json in it. The -N option of gzip will use the file name in the header (as well as the time stamp in the header), if there is one. So gzip -dN 1.gz would create the file my_latest_data.json, instead of 1.

You can find the file name in the header in Python by processing the header manually. You can find the details in the gzip specification.

  1. Verify that the first three bytes are 1f 8b 08.
  2. Save the fourth byte. Call it flags. If flags & 8 is zero, then give up -- there is no file name in the header.
  3. Skip the next six bytes.
  4. If flags & 2 is not zero, skip two bytes.
  5. If flags & 4 is not zero, then read the next two bytes. Considering them to be in little endian order, make an integer out of those two bytes, calling it xlen. Then skip xlen bytes.
  6. We already know that flags & 8 is not zero, so you are now at the file name. Read bytes until you get to zero byte. Those bytes up to, but not including the zero byte are the file name.
🌐
Dalkescientific
dalkescientific.com › writings › diary › archive › 2020 › 09 › 16 › faster_gzip_reading_in_python.html
Faster gzip reading in Python
September 16, 2020 - I am far from the first to point out that it's faster to use zcat than Python's gzip library. The xopen module, for example, can use the command-line pigz or gzip programs as a subprocess to decompress a file, then read from the program's stdout via a pipe.
🌐
Medium
medium.com › @anirudhbishnoi5 › gzip-module-in-python-230aafd7d17a
gzip module in Python. gzip is an inbuilt module in python… | by Anirudh Bishnoi | Medium
April 9, 2023 - syntax : gzip.open(filename, mode=’<mode-argument>’, compresslevel=<compression-level int value>,encoding=None) It is used to read or write into the files of gzip file object. It is very important to specify the filename.
🌐
Blogger
avrilomics.blogspot.com › 2018 › 10 › reading-and-writing-gzipped-files-in.html
avrilomics: Reading and writing gzipped files in Python
October 26, 2018 - I've highlighted the lines of the file that use the gzip module, and read and write from the input and output files. Very handy! import sys import os import gzip from collections import defaultdict #====================================================================# # now read in the input fastq and split it up: def read_fastq_file_and_split(input_fastq_file, seqs_per_output_file, output_file_prefix): # open an output file: output_file_cnt = 1 output_file = "%s_%d.fastq.gz" % (output_file_prefix, output_file_cnt) outputfileObj = gzip.open(output_file, "wb") # write out the output file in gzi
🌐
Python Module of the Week
pymotw.com › 2 › gzip
gzip – Read and write GNU zip files - Python Module of the Week
import gzip import os import hashlib def get_hash(data): return hashlib.md5(data).hexdigest() data = open('lorem.txt', 'r').read() * 1024 cksum = get_hash(data) print 'Level Size Checksum' print '----- ---------- ---------------------------------' print 'data d %s' % (len(data), cksum) for i in xrange(1, 10): filename = 'compress-level-%s.gz' % i output = gzip.open(filename, 'wb', compresslevel=i) try: output.write(data) finally: output.close() size = os.stat(filename).st_size cksum = get_hash(open(filename, 'rb').read()) print '] d %s' % (i, size, cksum) The center column of numbers in the
🌐
AskPython
askpython.com › python-modules › gzip-module-in-python
Python HowTo - Using the gzip Module in Python - AskPython
August 6, 2022 - In this article, we learned about how we can use the gzip module in Python, to read and write to .gz files.