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

2024-04-29 16:13:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谁知道为什么?

我试着写文件——在这种情况下也是这样。

例如

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

里面的文件是-?????????????????????????/

或者

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

另外,记事本不允许我用俄文字母保存文件。我给这个:

This file contains characters in Unicode format which will be lost if you save this file as an ANSI encoded text file. To keep the Unicode information, click Cancel below and then select one of the Unicode options from the Encoding drop down list. Continue?

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


Tags: 文件thetexttxtcloseunicode情况some
3条回答

下面是一个已完成的示例,请阅读注释:

#!/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

如果包含非ASCII字符,则需要定义文件编码。

http://www.python.org/dev/peps/pep-0263/

尝试使用编解码器打开文件,您需要

import codecs

然后

writefile = codecs.open('write.txt', 'w', 'utf-8')

相关问题 更多 >