5

I am trying to use:

text = "★"
file.write(text)

In python 3. But I get this error message:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0: ordinal not in range(128)

How can I print the symbol ★ in a file in python? This is the same symbol that is being used as star ratings.

TJ1
  • 7,578
  • 19
  • 76
  • 119
  • 8
    You'll want to use a different encoding. `with open('file.txt', 'w', encoding='utf-8') as f: f.write("★")` – cs95 Feb 20 '18 at 07:11
  • 2
    As long as Python lives, these pesky questions around Unicode will keep coming. I don't understand Python didn't get it right, even in v3. – nehem Feb 20 '18 at 07:22
  • @nehemiah I agree, I wish this was automatic in python so the programmer didn't need to take care of these details. – TJ1 Feb 20 '18 at 07:24
  • Possible duplicate of [Writing Unicode text to a text file?](https://stackoverflow.com/questions/6048085/writing-unicode-text-to-a-text-file) – Georgy Feb 20 '18 at 11:23

1 Answers1

7

By default open uses the platform default encoding (see docs):

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

This might not be an encoding that supports not-ascii characters as you noticed yourself. If you know that you want utf-8 then it's always a good idea to provide it explicitly:

with open(filename, encoding='utf-8', mode='w') as file:
    file.write(text)

Using the with context manager also makes sure there is no file handle around in case you forget to close or it throws an exception before you close the handle.

MSeifert
  • 145,886
  • 38
  • 333
  • 352