python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法

yipeiwu_com6年前Python基础

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

复制代码 代码如下:

import sys
print sys.getdefaultencoding()

执行:
复制代码 代码如下:

[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

 

相关文章

python批量修改文件名的实现代码

#coding:utf-8 #批量修改文件名 import os import re import datetime re_st = r'(\d+)\+\s?\((...

python DataFrame 取差集实例

需求:给定一个dataframe和一个list,list中存放的是dataframe中某一列的元素,删除dataframe中与list元素重复的行(即取差集)。 在网上搜了一圈,好像没看...

实例讲解Python中整数的最大值输出

在Python中可以存储很大的值,如下面的Python示例程序: x = 10000000000000000000000000000000000000000000; x = x...

python使用socket 先读取长度,在读取报文内容示例

本文实例讲述了python使用socket 先读取长度,在读取报文内容。分享给大家供大家参考,具体如下: tlpmts1:~/sbin # cat test9105.py # -*-...

python base64库给用户名或密码加密的流程

给明文密码加密的流程: import base64 pwd_after_encrypt = base64.b64encode(b'this is a scret!') pwd_bef...