【问题标题】:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 的字节 0xff
【发布时间】:2019-05-07 16:03:23
【问题描述】:
  1. 我尝试将 django 文件和 sqlite3 数据库文件迁移到 MySQL数据,我遇到了这样的错误。

  2. 创建数据库: 创建数据库 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>

【问题讨论】:

    标签: python json django


    【解决方案1】:

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

    确认'file_path'的编码格式:

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

    你应该没问题。

    【讨论】:

      【解决方案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'

      【讨论】:

        猜你喜欢
        • 2021-12-01
        • 2016-05-13
        • 2017-07-09
        • 2022-06-29
        • 1970-01-01
        • 2018-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多