当前位置: 首页 > 面试题库 >

如何将unicode字符串写入文件?

施驰
2023-03-14
问题内容

我正在使用python 2.6.5,我想向文件中写入一些日语字符。我收到此错误,并且我不知道如何更改编码。

Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
>>> s = u'\u5E73\u621015'
>>> with open("yop", "wb") as f:
...   f.write( s + "\n" );
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: 
  ordinal not in range(128)
>>> type( s )
<type 'unicode'>

问题答案:

您将需要对Unicode字符串进行“编码”。

s = u'\u5E73\u621015'
with open("yop", "wb") as f:
   f.write(s.encode("UTF-8"))

试试看一下,以方便地看一下unicode和python:http :
//farmdev.com/talks/unicode/



 类似资料: