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

2024-05-23 17:25:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python读取一个压缩文件(.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)

Tags: 模块文件import编码readlinestringlineutf
2条回答

也许

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

我不明白为什么这么难。

你到底在干什么?请解释“最终它读到一个无效字符”。

应该简单到:

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

编辑

这个答案对Python3中的Python2有效,请参见https://stackoverflow.com/a/19794943/610569上的@SeppoEnarvi的答案(它使用rt模式进行gzip.open)。

相关问题 更多 >