Hot For Coding
AttributeError 'module' object has no attribute 'setdefaultencoding'

Python的字符集处理实在蛋疼,目前使用UTF-8居多,默认使用的字符集是ascii,所以我们需要改成utf-8

查看目前系统字符集

import sys
print sys.getdefaultencoding()

Output:

[root@lee ~]# python a.py 
ascii

修改成utf-8

import sys
 
sys.setdefaultencoding('utf-8')
 
print sys.getdefaultencoding()

执行:

[root@lee ~]# python a.py 
Traceback (most recent call last):
  File "a.py", line 4, in <module>
    sys.setdefaultencoding('utf-8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'

提示错误: AttributeError: 'module' object has no attribute 'setdefaultencoding'

后来经过查找相关资料,才发现早期版本可以直接sys.setdefaultencoding('utf-8'),新版本需要先reload一下

import sys
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
print sys.getdefaultencoding()

执行:

[root@lee ~]# python a.py 
utf-8

TITLE: AttributeError 'module' object has no attribute 'setdefaultencoding'

LINK: https://www.qttc.net/332_python_attributeerror_module_object_has_no_attribute_setdefaultencoding.html

NOTE: 转载内容请注明出处