【问题标题】:UnicodeDecodeError When Opening a tar File in Python 3在 Python 3 中打开 tar 文件时出现 UnicodeDecodeError
【发布时间】:2017-07-05 18:04:18
【问题描述】:

我正在使用 Linux Mint 18.1 和 Python 3.5.2。

我有一个当前使用 Python 2.7 工作的库。我需要将该库用于 Python 3 项目。我正在更新它,但遇到了一个我似乎无法修复的 unicode 问题。

首先,通过tar cvjf tarfile.tbz2(在Linux系统上)创建一个文件,然后在Python库中以open(tarfile)打开。

如果我使用 Python 3 按原样运行代码,则会收到以下错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc1 in position 11: invalid start byte

我第一次尝试修复是将其打开为open(tarfile, encoding='utf-8'),因为我的印象是 tar 只会使用文件系统提供的内容。当我这样做时,我得到同样的错误(字节值改变)。

如果我尝试使用其他编码,比如latin-1,我会收到以下错误:

TypeError: Unicode-objects must be encoded before hashing

这让我相信utf-8 是正确的,但我可能会误解。

谁能提供建议?

【问题讨论】:

    标签: python-3.x tar python-unicode


    【解决方案1】:

    我走错了路,以为这是一些奇怪的编码问题。当open()默认读取为文本(r)这一事实只是一个简单的问题时。在 Python 2 中,这是一个空操作。

    解决方法是open(tarfile, 'rb')

    带有 unicode 的假头……应该看到这个来了。 :facepalm:

    【讨论】:

      猜你喜欢
      • 2014-03-11
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 2020-10-07
      • 2013-08-12
      相关资源
      最近更新 更多