f.write to solve python writing Chinese error
- 2021-01-14 06:05:05
- OfStack
1 example of an error
#coding:utf-8
s = u' Chinese '
f = open("test.txt","w")
f.write(s)
f.close()
The reason is that the encoding method is wrong, should be changed to utf-8 encoding
Solution 1:
#coding:utf-8
s = u' Chinese '
f = open("test.txt","w")
f.write(s.encode("utf-8"))
f.close()
Solution 2:
#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
s = u' Chinese '
f = open("test.txt","w")
f.write(s)
f.close()