读取文件编码错误

由于python中默认的编码是ascii,如果直接使用open方法得到文件对象然后进行文件的读写,都将无法使用包含中文字符(以及其他非ascii码字符),因此建议使用utf-8编码。为了避免读写错误,可以直接使用codecs模块。


下面的代码读取了文件,将每一行的内容组成了一个列表。 

import codecs
file = codecs.open('test.txt','r','utf-8')
lines = [line.strip() for line in file] 
file.close()

下面的代码写入了一行英文和一行中文到文件中。 

import codecs
file = codecs.open('test.txt','w','utf-8')
file.write('Hello World!
')
file.write('哈哈哈
')
file.close()
原文地址:https://www.cnblogs.com/mxhmxh/p/9367670.html