Alex Heebs
Alex Heebs

Reputation: 830

Python gives unicode error when writing to file

I'm trying to write to a file.

filename = "test.txt"
string = "Niñas and niños"

with open(filename, 'w') as element:
            element.write(string)

This returns the following error:

"Traceback (most recent call last):
  File "/Users/alex/Documents/Python/filewriter.py", line 5, in <module>
    element.write(string)
UnicodeEncodeError: 'ascii' codec can't encode character '\xf1' 
in position 2: ordinal not in range(128)"

I am using the latest version of Python, latest version of MacOS, and SublimeText3 as my editor.

Anyone have an idea what's going on?

Upvotes: 3

Views: 5090

Answers (1)

Hisagr
Hisagr

Reputation: 621

Open the file with utf-8 encoding, like this:

with open(filename, 'w', encoding='utf-8') as element:

Upvotes: 12

Related Questions