3

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?

wovano
  • 4,543
  • 5
  • 22
  • 49
Alan
  • 1,265
  • 4
  • 22
  • 44

2 Answers2

5

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()
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • You can't use `with` syntax unless you update Python (or use a newer interpreter if there's more than one installed). You can, of course, still use gzip files; you just need to close your handles explicitly. – Charles Duffy Feb 11 '18 at 21:52
  • 4
    @Alan, ...that said, any VPS that has a software stack from 2010 is going to be full of security risks. I'd be very, *very* wary of using it. – Charles Duffy Feb 11 '18 at 21:56
2

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:
    # ...

Sudharshann D
  • 935
  • 9
  • 9