AttributeError: 'GzipFile' object has no attribute '_buffer' when reading from gzip file

Viewed 7

When I attempt to read from a .gz file line by line with the gzip module in Python, I get a crash:

  File "/home/user/path/to/example.py", line 40, in run
    for line in handle:
  File "/home/user/.conda/envs/py38/lib/python3.10/gzip.py", line 399, in readline
    return self._buffer.readline(size)
AttributeError: 'GzipFile' object has no attribute '_buffer'

Here's my code:

import gzip

handle = gzip.open("path/to/file.txt.gz", "w")
for line in handle:
    print(line)

I'm using Python 3.10 on Linux.

1 Answers

The problem is that you have opened the file in write mode, not read mode.

Correct code:

import gzip

handle = gzip.open("path/to/file.txt.gz", "r")
for line in handle:
    print(line)

By changing the "w" to a "r" in the gzip.open() call, we choose to open the file in read mode rather than write mode.

(Note for reference: this error has a non-obvious cause and I couldn't find this elsewhere on here, so documenting both the error and the solution to help others)

Related