SMS Activate tiger-sms ChatGPT 账号/ChatGPT 代注册 OpenAI API 代充值

Linux 上用 Python 处理 Windows 上的 json 文件,提示 UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xef in position 9: ordinal not in range(128)

dajiaka OpenAI API key

今天把在 Windows 上写的 Python 文件传到 Linux 处理,功能很简单,就是读取 json 文件,做一点操作,但是在 print 的时候,提示我“UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xef in position 9: ordinal not in range(128)”,网上搜了一些解决办法没有效果,最后利用 sys 重新设置系统编码才搞定,这里记录下解决方法。

将这个错误 Google 了一下,排名最高的是 stackoverflow 上的一个回答,似乎问题跟我是一样的,回答者也给出了解决方法:

解决方法1:

>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1

解决方法2:

string.decode('utf-8')  # or:
unicode(string, 'utf-8')

但是这两个解决方法都没有解决我的问题。

最后看到一个博客的解决方法是利用 sys 重新设置编码,成功解决了这个错误,解决方式如下:

import sys  
reload(sys)
sys.setdefaultencoding('utf-8')
赞(1)
关注我们
未经允许不得转载:老王博客 » Linux 上用 Python 处理 Windows 上的 json 文件,提示 UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xef in position 9: ordinal not in range(128)