使用codecs
模塊,並確保您要寫入文件的內容是unicode
。 (有關更多詳細信息,請參閱Kumar McMillan的talk from PyCon 2008)。
下面是如何使用codecs
模塊將俄文和普通話中文字符寫入文件的最簡單示例。
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
def to_unicode_or_bust(obj, encoding='utf-8'):
## by Kumar McMillan (http://farmdev.com/talks/unicode/)
if isinstance(obj, basestring):
if not isinstance(obj, unicode):
obj = unicode(obj, encoding)
return obj
mystring = 'String input: УТВЕРЖДЕНО, 項目名稱\n'
mystring_unicode = u'Unicode input: УТВЕРЖДЕНО, 項目名稱\n'
with codecs.open("filename.txt", 'a', encoding='utf-8') as stream:
stream.write(to_unicode_or_bust(mystring))
stream.write(to_unicode_or_bust(mystring_unicode))
你不需要使用utf-8嗎? – Ashalynd 2014-09-02 17:41:39
我也使用過,仍然有問號出現 – GBh 2014-09-02 17:44:25
我可以使用編解碼器來編碼字符嗎? – GBh 2014-09-03 21:05:58