有中文,有英文;出现如下错误:
这是我的基本操作:
这是输出结果
麻烦各位看看了啊
不加encode也会出现如下错误:
报错信息是编码相关的问题,我的测试程序,可以参考下:
# 测试的文本
[root@ZTEST-163 py]# cat t.txt
hello
world
你好
世界
# 测试py脚本
[root@ZTEST-163 py]# cat open.py
#coding: utf-8
file_path = '/home/test/py/t.txt'
with open(file_path, 'r') as fd:
cnt = fd.read()
print cnt
# 运行结果
[root@ZTEST-163 py]# python open.py
hello
world
你好
世界
ps:unicode才能编码成指定的格式,所以在编码的时候,首先要确定被编码的字符是unicode的。比如,要将gb2312的编码成utf-8的,过程如下:
s = s.decode('gb2312')
s = s.encode('utf-8')
7 回答5.3k 阅读
4 回答4k 阅读
2 回答5.9k 阅读✓ 已解决
2 回答2.5k 阅读✓ 已解决
1 回答2.4k 阅读✓ 已解决
2 回答826 阅读✓ 已解决
2 回答3.3k 阅读
不需要 encode