python写utf-8文件的问题


import codecs

txt = u"\u5e10\u53f7\u4e0d\u5b58\u5728"
file=codecs.open("test","w","utf-8")
file.write(txt)
file.close()

这个可以正确写入
但当string只为ascii字符时,比如

txt = u"qwer"

这时生成的file仍旧为ascii格式
需要怎么做才能生成utf-8格式的文件?
谢谢

python utf-8

爆炸小卷子 11 years, 4 months ago
import codecs
txt = u"qwer"
file=codecs.open("test","w","utf-8-sig")
file.write(txt)
file.close()
飙车的神父 answered 11 years, 4 months ago

Your Answer