Avoid producing mojibake by assuming UTF-8
mainTo prevent mojibake (encoding errors), assume text is in UTF-8 unless you have a specific reason to believe otherwise. In Python 3, use the Unicode string type (str) for all operations.
When opening text files, explicitly specify the encoding as utf-8 and use errors='replace' to handle potential issues gracefully:
openfile = open(filename, encoding='utf-8', errors='replace')When converting bytes to text, decode them as UTF-8:
text = bytebuffer.decode('utf-8', 'replace')