0

I get the following error when try to write in file:

UnicodeEncodeError('ascii', u'B\u1ea7u cua (B\u1ea7u cua 2017 )', 1, 2, 'ordinal not in range(128)'))

I try to write this text Bầu cua in file:

f = codecs.open("13.txt", "a", "utf-8")
f.write("{}\n".format(title))

Also I tried to use title.encode()

It gives me a new error:

When I use .encode(text) I get the following error: `

UnicodeDecodeError('ascii', 'B\xe1\xba\xa7u cua (B\xe1\xba\xa7u cua 2017 )\n', 1, 2, 'ordinal not in range(128)'))
`
4
  • Possible duplicate of Writing Unicode text to a text file? Commented Dec 15, 2016 at 9:13
  • I have read this queastion also, and tried all advices Commented Dec 15, 2016 at 9:14
  • It does not work foe me http://stackoverflow.com/a/6048203/7041624 Commented Dec 15, 2016 at 9:15
  • @MisterPi we can put encoding type at the start of file Commented Dec 15, 2016 at 13:06

2 Answers 2

2

As described this answer to "Writing Unicode text to a text file?", you have many solutions.

Basically, you have 2 issues:

The str.format() method must be used on an unicode object

u'{}\n'.format('Bầu cua')

The file you write to also must be opened with the right encoding:

f = open('13.txt', 'a', encoding='utf-8')

As a result, this works for Python 3:

data = 'Bầu cua'
f = open('13.txt', 'a', encoding='utf-8')
line = u'{}\n'.format(data)
f.write(line)
f.close()
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I applied your answer and now get error: UnicodeDecodeError('ascii', 'Volkswagen Golf GTI \xe2\x80\x93 EBG\n', 20, 21, 'ordinal not in range(128)'))
Notice please attention on my comment
0

Try with these two lines at the beginning of the file. It works well for Python2.7

#!/usr/bin/env python
# -*- coding: utf-8 -*-

data = u'Bầu cua'
f = open('test.txt', 'a')
line = u'{}\n'.format(data)
f.write(line.encode('utf8'))
f.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.