首页 > 代码库 > 解决Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode异常错误

解决Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode异常错误

一、原由

1.python默认使用ASCII处理字符流

2.Unicode编码与ASCII编码的不兼容,Python脚本文件是由utf-8编码的

Traceback (most recent call last):
  File "makedb.py", line 33, in 
    main()
  File "makedb.py", line 30, in main
    fp.write(row[1])
UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 0-78: ordinal not in range(128)

二、解决方案:

导入sys模块,

import sys
def main():
        reload(sys)
        sys.setdefaultencoding(‘utf-8‘)

  

解决Python2.7的UnicodeEncodeError: ‘ascii’ codec can’t encode异常错误