The program below triggers a UnicodeEncodeError on my Windows 10 machine (running Python 3.5.2) but no error at all on my Linux machine (running Python 3.3.2).
#!/usr/bin/python
import logging
str ="Antonín Dvořák"
logging.basicConfig(filename='log.txt', level=logging.INFO)
logging.info(str)
On Linux, the log file correctly contains:
INFO:root:Antonín Dvořák
On Windows, I get the following error:
Any ideas on what the possible cause could be for this discrepancy?
Theh default encoding of Windows (cp1252 in your case) is different from Linux (usually utf8), so you have to specify the encoding you want.
Below didn't work in Python 3.3 (still used cp1252) but did with 3.5 so it looks like a bug in 3.3. I used utf-8-sig
because many Windows text editors default to an ANSI encoding (such as cp1252) without a UTF-8 BOM signature.
import logging
str ="Antonín Dvořák"
with open('log.txt','w',encoding='utf-8-sig') as s:
logging.basicConfig(stream=s, level=logging.INFO)
logging.info(str)
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