Python 2与Python 3区别之记录

python 2.7与python 3.6使用中的区别记录
(在此博客发布之前用的都是2.7,之后从3.6开始)

print

  • python 2

打印到console:

print 'Hello World!'

打印到文件

test_file = open('test.txt', 'w')
print >> test_file, 'Hello World!'
  • python 3

打印到console:

print('Hello World!')

打印到文件:

test_file = open('test.txt', 'w')
print('Hello World!', file='test.txt')
# 注意必须指定file=file_name,以下格式会打印到控制台
print('Hello World!', 'test.txt')
# 上面语句默认file=None

json文件有中文时: json.load

  • python 2
with open('test.json', 'r') as file_content:
   json_string = json.load(file_content)
   file_content.close()
  • python 3
    直接用python 2的load的方式,会报以下错误:
 UnicodeEncodeError: 'gbk' codec can't encode character '\xae' in position 60975: illegal multibyte sequence

改为在open的时候指定encoding的编码方式:

with open('test.json', 'r', encoding='utf-8') as file_content:
   json_string = json.load(file_content)
   file_content.close()

reload(sys)

python 2在兼容中文时会加上以下语句:

reload(sys)
sys.setdefaultencoding("utf-8")

然而reload语句在python 3中是会报错的,python 3中已经很好的支持了中文,所以将以上两个删掉就好

猜你喜欢

转载自blog.csdn.net/u010895119/article/details/78798498