如何在zip中打开unicode文本文件?

 悲剧制造商_469 发布于 2023-02-10 11:58

我试过了

with zipfile.ZipFile("5.csv.zip", "r") as zfile:
    for name in zfile.namelist():
        with zfile.open(name, 'rU') as readFile:
                line = readFile.readline()
                print(line)
                split = line.split('\t')

它回答:

b'$0.0\t1822\t1\t1\t1\n'
Traceback (most recent call last)
File "zip.py", line 6
    split = line.split('\t')
TypeError: Type str doesn't support the buffer API

如何打开文本文件作为unicode而不是b

2 个回答
  • 要将字节流转换为Unicode流,您可以使用io.TextIOWrapper():

    encoding = 'utf-8'
    with zipfile.ZipFile("5.csv.zip") as zfile:
        for name in zfile.namelist():
            with zfile.open(name) as readfile:
                for line in io.TextIOWrapper(readfile, encoding):
                    print(repr(line))
    

    注意:TextIOWrapper()默认情况下使用通用换行模式.自3.4版以来rU,zfile.open()不再使用mode in .

    它避免了@Peter DeGlopper的回答中描述的多字节编码问题.

    2023-02-10 12:01 回答
  • 编辑对于Python 3,使用io.TextIOWrapper作为这个答案介绍是最好的选择。以下答案对于2.x可能仍然有用。我认为即使对于3.x,下面的任何内容实际上都不是错误的,但io.TestIOWrapper仍然更好。

    如果文件是utf-8,则可以使用:

    # the rest of the code as above, then:
    with zfile.open(name, 'rU') as readFile:
        line = readFile.readline().decode('utf8')
        # etc
    

    如果您要遍历可以使用的文件codecs.iterdecode,则无法使用readline()

    with zfile.open(name, 'rU') as readFile:
        for line in codecs.iterdecode(readFile, 'utf8'):
            print line
            # etc
    

    注意,这两种方法对于多字节编码都不一定是安全的。例如,小尾数UTF-16用bytes表示换行符b'\x0A\x00'。一个寻找换行符的非Unicode感知工具将错误地将其拆分,从而在下一行保留空字节。在这种情况下,您必须使用不会尝试用换行符分隔输入的内容,例如ZipFile.read,然后立即解码整个字节字符串。这不是utf-8的问题。

    2023-02-10 12:01 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有