How to write Russian characters in file?

拈花ヽ惹草 提交于 2019-11-29 09:58:19

Here is a worked-out example, please read the comments:

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

Try opening the file using codecs, you need to

import codecs

and then

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

You need to define file encoding if it contains non-ASCII chars.

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

What console are you using? Chances are, your console doesn't support that language. Make sure that your console supports Unicode (and that your app is sending Unicode strings).

Update:

To address the update to your question regarding problems with Windows' Notepad: Click File->Save As, and then choose "Unicode" from the "Encoding" drop-down list.

Are you typing in console too or only seing the results in console? This looks a pep-0263 problem as petraszd said.

print p.decode('your-system-encoding')

should work in console (I don't know what is the encoding system you use for Russian)

If you are using a .py file, you need to place # -*- coding: UTF-8 -*- (replacing utf-8 with Rusian encoding) on the top of the file and I think there is no need for the .decode in print if your OS is configured with the right encoding. (at least I don't need it but I don't know how it works with Russian)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!