Tuesday 15 February 2011

How to write cyrillic letters to a file in Python/Django -



How to write cyrillic letters to a file in Python/Django -

i have big form contains lot of text. example, may contain words in quotation marks "Программа". when submit server , seek write submitted content file, error. if instead replace cyrillic letters latin letters, works ok. problem on server side. guess, if new how deal such strings "Текст на кириллице", solve problem.

when write file unicode string, must encode first.

let's seek following:

# -*- coding: utf-8 -*- text = u"Текст на кириллице" open('outfile.txt', 'w') fw: fw.write(text)

this code raise exception

unicodeencodeerror: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

so, encode text. 1 of popular encoding 'utf8':

# -*- coding: utf-8 -*- text = u"Текст на кириллице" open('outfile.txt', 'w') fw: fw.write(text.encode('utf8'))

you must remember encoding, used encode text, able read later. read text file, decode using same encoding used in writting:

with open('outfile.txt') f: text = f.read() print text.decode('utf8')

python django

No comments:

Post a Comment