Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: writing ★ in a file

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.

like image 916
TJ1 Avatar asked Mar 07 '23 20:03

TJ1


1 Answers

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.

like image 196
MSeifert Avatar answered Mar 16 '23 20:03

MSeifert