I have a word in Polish as a string variable which I need to print to a file:
# coding: utf-8
a = 'ilośc'
with open('test.txt', 'w') as f:
print(a, file=f)
This throws
Traceback (most recent call last):
File "C:/scratches/scratch_3.py", line 5, in <module>
print(a, file=f)
File "C:\Python34\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 '\u015b' in position 3: character maps to <undefined>
Looking for existing answers (with .decode("utf-8")
, or with .encode("utf-8")
) and trying various incantations I finally managed the file to be created.
Unfortunately what was written was b'ilośc'
and not ilośc
. When I tried to decode that before printing to the file, I got back to the initial error and the same traceback.
How to write a str
containing diacritics to a file so that it is a string and not a bytes representation?