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)'))
`
MisterPi
  • 1,471
  • 5
  • 17
  • 23

2 Answers2

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()
Community
  • 1
  • 1
Antwane
  • 20,760
  • 7
  • 51
  • 84
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()
Shivkumar kondi
  • 6,458
  • 9
  • 31
  • 58