【问题标题】:Reading contents of zip file without extracting无需解压即可读取 zip 文件的内容
【发布时间】:2016-05-29 04:38:13
【问题描述】:

我想要实现的示例:

我的文本文件 (test1.txt) 包含以下两行:

John scored 80 in english

tim scored 75 in english

我已将此文件压缩为test1.zip,并尝试使用以下代码读取内容:

f = 'test1.zip'
z = zipfile.ZipFile(f, "r")
zinfo = z.namelist()
for name in zinfo:
    with z.open(name) as f1:
        fi1 = f1.readlines()
for line in fi1:
print(line)

但我得到的结果是

b'John scored 80 in english\r\n'

b'tim scored 75 in english\r\n'

如何读取这个 zip 文件的内容,它应该给我与原始文件内容相同的输出:

John scored 80 in english

tim scored 75 in english

【问题讨论】:

  • 你得到了原始输入。

标签: python-3.x zip zipfile


【解决方案1】:

您实际上正在阅读文件中的确切内容。

/r/n 字符是 windows 中的换行符。问题 Difference between \n and \r? 更详细一点,但归根结底是 Windows 使用 /r/n 作为其换行符。

您看到的 b' 字符与 python 以及它如何解析文件有关。问题What does the 'b' character do in front of a string literal? 很好地回答了为什么会发生这种情况,但引用的文档是:

字节文字总是以'b'或'B'为前缀;他们产生一个 bytes 类型而不是 str 类型的实例。他们可能只 包含 ASCII 字符;数值为 128 或更大的字节 必须用转义符表示。

编辑:我实际上找到了一个非常相似的答案,您可以从中提取而不需要额外的字符:py3k: How do you read a file inside a zip file as text, not bytes?。基本的想法是你可以使用这个:

items_file  = io.TextIOWrapper(items_file, encoding='your-encoding', newline='')

【讨论】:

    【解决方案2】:

    使用print(line.decode('ascii').strip()) 代替print(line)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 2017-10-21
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      • 2023-01-03
      相关资源
      最近更新 更多