【问题标题】:Python - Read a file which contains bytes and stringsPython - 读取包含字节和字符串的文件
【发布时间】:2020-10-19 08:26:42
【问题描述】:

我在 python 中开发一个程序,该程序分析文件并仅在这些文件中保留我想要的内容。 打开某些文件时出现错误。这些文件包含这样的字符串和字节:

file.py:
if byte == "0xFD":
    for byte in bytes.split["0xFD"]:
...

当我打开该类型的文件时,引号之间的字符串被解释为字节,这会使程序崩溃: UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 59752: character maps to <undefined>。 'utf-8' 出现同样的错误。

所以我的问题是:如何在不解释字节的情况下读取该行(我想保持这样的行)?

【问题讨论】:

    标签: python file encoding byte


    【解决方案1】:

    如果您在open 函数中添加rb,它会将字节读取为UTF-8。

    file = open("insertfilenamehere.txt", "rb")
    txt = file.read()
    

    【讨论】:

    • 导致这个错误:TypeError: a bytes-like object is required, not 'str'
    【解决方案2】:

    我找到了一种方法来做我想做的事: with open(file_path, "r", encoding="utf-8", errors='replace') as file:

    我在这篇文章中找到了一些帮助:Unicode error handling with Python 3's readlines()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-28
      • 2011-12-18
      • 2016-07-17
      • 2023-03-05
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多