John M.
John M.

Reputation: 875

Read gz file as a string in Python

I have been searching for a way that could read gz file in python, and I did something like

with gzip.open(filepath) as infile:
    ...

However, it seems like the read-in data is byte-like and I cannot do something like for l in infile. Is there a way to solve this?

Upvotes: 4

Views: 6423

Answers (1)

Joe Iddon
Joe Iddon

Reputation: 20414

Pass mode='rt' (text mode) to the gzip.open call.

From the documentation (linked above):

The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x' or 'xb' for binary mode, or 'rt', 'at', 'wt', or 'xt' for text mode. The default is 'rb'.

Upvotes: 6

Related Questions