GzipFile instance has no attribute '__exit__' when used in a "with:" block

Question:

I need to process a .gz file with Python.

I pass the filename into my Python script with:

infile = sys.argv[1]

with gzip.open(infile, 'rb') as f:
    logfile = f.read()

which gives me:

with gzip.open(infile, 'rb') as f:
AttributeError: GzipFile instance has no attribute '__exit__'

If I manually gunzip my .gz file and then pass that to my Python script, all works fine.

logfile = open(infile, 'r').read()

NB: I’m using Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37). I don’t have the ability to update Python on this computer. How can I process a gzipped text file with Python 2.6?

Asked By: Alan

||

Answers:

Context manager support for the gzip module is issue 3860.

It was fixed in Python 3.1 alpha 1 (in the 3.x line) and 2.7 alpha 1 (in the 2.x line). It’s still open in 2.6.6, which you’re using here.


Of course, you can work around this by just not using context-manager syntax:

import sys, gzip

logfile = gzip.open(sys.argv[1], 'rb').read()
Answered By: Charles Duffy

This answers highlights the use of contextlib to call the close method.

with contextlib.closing(gzip.open(inputFileName,'rb')) as openedFile:
    # processing code 
    # for line in openedFile:
    # ...

Answered By: Sudharshann D
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.