扫码关注官方订阅号
有中文,有英文;出现如下错误:这是我的基本操作:这是输出结果麻烦各位看看了啊
不加encode也会出现如下错误:
认证高级PHP讲师
不需要 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')
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
不需要 encode
报错信息是编码相关的问题,我的测试程序,可以参考下:
ps:unicode才能编码成指定的格式,所以在编码的时候,首先要确定被编码的字符是unicode的。比如,要将gb2312的编码成utf-8的,过程如下:
s = s.decode('gb2312')
s = s.encode('utf-8')