从python中的gzip文件中读取utf-8字符

Jua*_*esa 27 python file-io gzip utf-8

我试图在python中读取一个gunzipped文件(.gz),但我遇到了一些麻烦.

我使用gzip模块读取它,但文件被编码为utf-8文本文件,因此最终它会读取无效字符并崩溃.

有谁知道如何读取编码为utf-8文件的gzip文件?我知道有一个编解码器模块可以提供帮助,但我无法理解如何使用它.

谢谢!

import string
import gzip
import codecs

f = gzip.open('file.gz','r')

engines = {}
line = f.readline()
while line:
    parsed = string.split(line, u'\u0001')

    #do some things...

    line = f.readline()
for en in engines:
  print(en)
Run Code Online (Sandbox Code Playgroud)

Sep*_*rvi 37

这在Python 3.3中是可能的:

import gzip
gzip.open('file.gz', 'rt', encoding='utf-8')
Run Code Online (Sandbox Code Playgroud)

请注意,gzip.open()要求您明确指定文本模式('t').


小智 21

我不明白为什么这应该这么难.

你在做什么?请解释"最终它会读取无效字符".

应该这么简单:

import gzip
fp = gzip.open('foo.gz')
contents = fp.read() # contents now has the uncompressed bytes of foo.gz
fp.close()
u_str = contents.decode('utf-8') # u_str is now a unicode string
Run Code Online (Sandbox Code Playgroud)

EDITED

这个答案适用Python2Python3,请参阅@SeppoEnarvi的回答/sf/answers/1385646041/(它使用的rt模式为gzip.open.


Joc*_*zel 21

也许

import codecs
zf = gzip.open(fname, 'rb')
reader = codecs.getreader("utf-8")
contents = reader( zf )
for line in contents:
    pass
Run Code Online (Sandbox Code Playgroud)

  • 作为一个单行:for codecs.getreader('utf-8')(gzip.open(fname),errors ='replace')中的行,它还增加了对错误处理的控制 (3认同)

Yur*_*rik 5

以上产生了大量的解码错误.我用过这个:

for line in io.TextIOWrapper(io.BufferedReader(gzip.open(filePath)), encoding='utf8', errors='ignore'):
    ...
Run Code Online (Sandbox Code Playgroud)