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.
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 thecodecs
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With