1. 程式人生 > >python中 f.write寫入中文出錯解決方法

python中 f.write寫入中文出錯解決方法

一個出錯的例子

#coding:utf-8
s = u'中文'
f = open("test.txt","w")
f.write(s)
f.close()

原因是編碼方式錯誤,應該改為utf-8編碼

解決方案一:

#coding:utf-8
s = u'中文'
f = open("test.txt","w")
f.write(s.encode("utf-8"))
f.close()

解決方案二:

複製程式碼
#coding:utf-8
import sys

reload(sys)
sys.setdefaultencoding('utf-8') 

s = u'中文'
f = open("
test.txt","w") f.write(s) f.close()
複製程式碼