首页 > python文件读取出现便马上的错误,该怎么解决啊?

python文件读取出现便马上的错误,该怎么解决啊?

有中文,有英文;出现如下错误:
这是我的基本操作:

这是输出结果

麻烦各位看看了啊


不加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')


不需要 encode

【热门文章】
【热门文章】