python默认的写文件编码弄不清具体是什么编码格式,只发现中文字体写入默认是GB2312编码。
要想指定读取和写入文件的编码格式,只需要用如下方法。
一、不指定编码格式:
with open(file,'a') as f:
('要写入文件的内容')
二、指定编码格式:
指定编码写入,需要打开文件的时候按指定的编码写入,open第三个参数写encoding编码方式。(with的这种方式,会自动close()释放资源)
filename = ''
#使用‘w’来提醒python用写入的方式打开 指定编码为
with open(filename,'w',encoding='utf-8') as fileobject: utf-8
('I love your name!'
'\nI love your cloth!'
'\nI love your shoes!'
'\nI love your hair!')
#使用‘a’来提醒python用附加模式的方式打开指定编码为
with open(filename,'a',encoding='utf-8') as fileobject: utf-8
('\nI an superman.')
如果不用with的写法
# 1. 打开
file = open("", "a",encoding='utf-8' ) # a 以追加的方式打开 (默认以只读方式打开)
# 2. 写入文件
("123 hello")
# 3. 关闭
()