Skip to content Skip to sidebar Skip to footer

Unicodeencodeerror Writing Text With Special Character To File

I get a UnicodeEncodeError writing text with a special character to a file: File 'D:\SOFT\Python3\lib\encodings\cp1252.py', line 19, in encode return codecs.charmap_encode(in

Solution 1:

Your problem is that opening in text mode on your Windows system defaulted to the locale code page, cp1252, an ASCII superset that only encodes a tiny fraction of the Unicode range.

To fix, supply a more comprehensive encoding that can support the whole Unicode range; open accepts a keyword argument to override the default encoding, so it's as simple as changing:

expFile = open(expFilePath, 'w')

to

expFile = open(expFilePath, 'w', encoding='utf-8')

Depending on your needs, I'd choose either utf-8 or utf-16; the former is more compact for mostly ASCII text, and is commonly seen everywhere, while the latter matches Microsoft's typical encoding for storing portable (non-locale dependent) text, so it's possible a few Windows-specific text editors would recognize it/handle it more easily.

Post a Comment for "Unicodeencodeerror Writing Text With Special Character To File"