python文件读写出现乱码总结

时间:2022-04-23
本文章向大家介绍python文件读写出现乱码总结,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.错误的打开方式

#coding=utf-8f = open("test.txt",'w+')f.write('Mars is slim,isn'he? n 火星教')print f.read()f.close()

控制台结果:

2.正确的打开方式

建议在进行写入操作后先将文件关闭,然后再打开,最后再读取文件

若你的txt文件编码是utf-8,则需要在f.read()添加decode('utf-8'),即f.read().decode('utf-8')即可         

代码如下:

#coding=utf-8#这样写,对文件进行读写操作之后打开记事本不会乱码f = open("test.txt",'w+')f.write('Mars is slim,isn'he? n 火星教')f.close()f = open("test.txt").decode('utf-8')print f.read()f.close()

结果显示: