2

I am getting the following error:

Traceback (most recent call last):
File "C:\Books\Python\gsearch.py", line 21, in <module>
  text_file.write(titles)
File "C:\Program Files\Python 3.5\lib\encodings\cp1252.py", line 19, in encode
  return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2190' in position 2936: character maps to <undefined>

The line text_file.write(titles) is supposed to write some text stored in the titles variable to a file. I have read other questions like this one on Stackoverflow. However, they specifically deal with console output using print. I want to write the text to a file.

Community
  • 1
  • 1
Neena Vivek
  • 667
  • 7
  • 19
  • Briefly: when you open a file that contains or will contain Unicode characters, specify a Unicode encoding. – TigerhawkT3 Jan 02 '17 at 05:57
  • Also, I copy-pasted your question's exact title into a Google search, and the relevant duplicate was the fourth result. – TigerhawkT3 Jan 02 '17 at 05:58

1 Answers1

4

You have to specify a proper encoding for your file object at opening time. This can be done by passing the encoding to encoding keyword argument of open() function.

For example:

with open(file_name, 'w', encoding='utf8') as text_file:
    pass
Mazdak
  • 105,000
  • 18
  • 159
  • 188