Read from a gzip file in python

PythonPython 2.7Gzip

Python Problem Overview


I've just make excises of gzip on python.

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

And I get no output on the screen. As a beginner of python, I'm wondering what should I do if I want to read the content of the file in the gzip file. Thank you.

Python Solutions


Solution 1 - Python

Try gzipping some data through the gzip libary like this...

import gzip
content = "Lots of content here"
f = gzip.open('Onlyfinnaly.log.gz', 'wb')
f.write(content)
f.close()

... then run your code as posted ...

import gzip
f=gzip.open('Onlyfinnaly.log.gz','rb')
file_content=f.read()
print file_content

This method worked for me as for some reason the gzip library fails to read some files.

Solution 2 - Python

https://stackoverflow.com/questions/10566558/python-read-lines-from-compressed-text-files

Using gzip.GzipFile:

import gzip

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

Solution 3 - Python

If you want to read the contents to a string, then open the file in text mode (mode="rt")

import gzip

with gzip.open("Onlyfinnaly.log.gz", mode="rt") as f:
    file_content = f.read()
    print(file_content)

Solution 4 - Python

for parquet file, pls using pandas to read

data = read_parquet("file.parquet.gzip")
data.head()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichaelView Question on Stackoverflow
Solution 1 - PythonMatt OlanView Answer on Stackoverflow
Solution 2 - PythonArunava GhoshView Answer on Stackoverflow
Solution 3 - PythonMichael HallView Answer on Stackoverflow
Solution 4 - PythonFan YangView Answer on Stackoverflow