如何在文件中写俄语字符?


问题内容

在控制台中,当我尝试输出俄语字符时,它会给我???????????????

谁知道为什么?

我尝试写入文件-在这种情况下,情况相同。

例如

f=open('tets.txt','w')
f.write('some russian text')
f.close

内部文件是-???????????????????????????? /

要么

p="some russian text"
print p
?????????????

在其他记事本中,不允许我使用俄语字母保存文件。我给这个:

该文件包含Unicode格式的字符,如果将该文件另存为ANSI编码的文本文件,这些字符将丢失。要保留Unicode信息,请单击下面的“取消”,然后从“编码”下拉列表中选择Unicode选项之一。继续?

如何调整我的系统,这样我就不会有这个问题。


问题答案:

这是一个可行的示例,请阅读注释:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# The above encoding declaration is required and the file must be saved as UTF-8

from __future__ import with_statement   # Not required in Python 2.6 any more

import codecs

p = u"абвгдежзийкл"  # note the 'u' prefix

print p   # probably won't work on Windows due to a complex issue

with codecs.open("tets.txt", "w", "utf-16") as stream:   # or utf-8
    stream.write(p + u"\n")

# Now you should have a file called "tets.txt" that can be opened with Notepad or any other editor