UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff

Posted

技术标签:

【中文标题】UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff【英文标题】:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0 【发布时间】:2019-05-07 16:03:23 【问题描述】:

    我尝试将 django 文件和 sqlite3 数据库文件迁移到 mysql数据,我遇到了这样的错误。

    创建数据库: 创建数据库 mysite_db 默认字符集=utf8mb4 默认整理 utf8mb4_unicode_ci;

    db_sqlite3 中的数据迁移: python manage.py dumpdata > data.json

    输入mysql: python manage.py loaddata data.json


File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 113, in loaddata
    self.load_label(fixture_label)
  File "C:\blog_env\lib\site-packages\django\core\management\commands\loaddata.py", line 168, in load_label
    for obj in objects:
  File "C:\blog_env\lib\site-packages\django\core\serializers\json.py", line 66, in Deserializer
    stream_or_string = stream_or_string.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
(blog_env) PS C:\blog_env\mysite>

【问题讨论】:

【参考方案1】:

我最近遇到了同样的问题...这是我的解决方案:

确认'file_path'的编码格式:

    下载并使用记事本++打开文件 检查右下角;在那里你可以看到你的文件是否以兼容的格式编码,或者它是否有字节顺序标记或 BOM 标志, 如果其中任何一个为真,只需“另存为”正确/必需的格式即可。

你应该没问题。

【讨论】:

【参考方案2】:

只需从错误发生的地方转到文件的位置即可。

在我的情况下,错误来自序列化程序中的 json.py 文件,因为我的错误如下:

File "C:\Users\User\AppData\Local\Programs\Python\Python38\Lib\site-packages\django\core\serializers\json.py",line 66 in Deserializer stream_or_string = stream_or_string.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

进入 location 后,只需用您的空闲或记事本打开 json.py 文件,这样您就可以编辑该文件。直接进去Deserializer函数就行了:

stream_or_string = stream_or_string.decode()

并将这一行更改为

stream_or_string = stream_or_string.decode('UTF-16')

并保存,现在您的错误将得到解决。

【讨论】:

解决了!我的问题..【参考方案3】:

部分与上述亚伯拉罕解决方案..

如果您使用 VS Code,请查看右下角,它可能会显示类似 UTF- 的内容。我的是UTF-16。只需单击它,然后单击“使用编码保存”,然后选择“utf-8”。我一直忘记来自 CLI 的某些命令在创建文件时会将它们创建为 UTF-8(在 powershell 中运行时的某些命令)$PSDefaultParametervalues['Out-File:Encoding'] = 'utf8'

【讨论】:

以上是关于UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff的主要内容,如果未能解决你的问题,请参考以下文章

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte...

UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff

UnicodeDecodeError:“utf-8”编解码器无法解码位置 34 中的字节 0x85:无效的起始字节

UnicodeDecodeError:“utf-8”编解码器无法解码位置 35 中的字节 0x96:无效的起始字节

UnicodeDecodeError:“utf-8”编解码器无法解码位置 1023 中的字节 0xe2:数据意外结束

UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xc0 in position 0: invalid start byte报错解决