1

I am getting a message 'ascii' codec can't encode character u'\xe9' when I am writing a string to my file, heres how I am writing my file

my_file = open(output_path, "w")
my_file.write(output_string)
my_file.close()

I have been searching and found answers like this UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128) and the first one didn't work and then this one I'm confused why I am encoding data I want to be able to read

import io

f = io.open(filename, 'w', encoding='utf8')

Thanks for the help

Community
  • 1
  • 1
spen123
  • 3,464
  • 11
  • 39
  • 52
  • 1
    ASCII is a 7-bit encoding. There's no such value as ASCII E9. – Jon Skeet Jul 29 '15 at 20:52
  • @JonSkeet what do you mean? this is what I am getting as errors `UnicodeEncodeError: 'ascii' codec can't encode character u'\x96' in position 62393: ordinal not in range(128)` and `UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 343071: ordinal not in range(128)` when I write my string to file – spen123 Jul 29 '15 at 20:55
  • "Why I am encoding data I want to be able to read"—there is no text but encoded text. – Tom Blodget Jul 29 '15 at 21:45
  • @spenf10: Well yes, because that character isn't in ASCII. That's what I mean. The unicode character you're referring to is U+00E9. That isn't in ASCII, so trying to encode it in ASCII doesn't work. Use a different encoding. Note that to write text to a file, you *always* encode it - an encoding is just a mapping from text to binary data. – Jon Skeet Jul 29 '15 at 22:07

1 Answers1

0

As mentioned, you're trying to write non-ASCII characters with the ASCII encoding. Since the built-in open function doesn't support the encoding parameter, then consider always using io.open in Python 2.7 (which is the default since Python 3.x).

cdonts
  • 9,304
  • 4
  • 46
  • 72