python with open as f写中文乱码
python3和python2的写法不一样具体如下:
python3:
with open(r'd:\ssss.txt','w',encoding='utf-8') as f:
f.write(u'中文')
python2中open方法是没有encoding这个参数的,如果像python3一样的写法会报异常:TypeError: 'encoding' is an invalid keyword argument for this function
python2中需要加上:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
with open(r'd:\sss.txt','w') as f:
f.write(unicode("\xEF\xBB\xBF", "utf-8"))#函数将\xEF\xBB\xBF写到文件开头,指示文件为UTF-8编码。
f.write(u'中文')
读取文件
with open(r'd:\aaa.txt','r') as ff:
a= ff.read().encode('gbk')#编码为gbk输出 控制台
print a
或者还有一种写法:
import io
with io.open(path,'w',encoding='utf-8') as f:
f.write(unicode("\xEF\xBB\xBF", "utf-8"))#函数将\xEF\xBB\xBF写到文件开头,指示文件为UTF-8编码。
f.write(u'这是中文')
with open(r'd:\aaa.txt','r') as ff:
a= unicode(ff.read(),'utf-8')#编码为UTF-8输出
print a