How do you correctly handle character encoding when reading text files that might not be UTF-8, and what error occurs if you guess wrong?
Short answer
Explicitly pass the 'encoding' parameter to open() (e.g., encoding='latin-1' or 'utf-8') rather than relying on the platform-dependent default — reading a file with the WRONG encoding raises a UnicodeDecodeError (for incompatible byte sequences) or silently produces GARBLED text…
Advertisement
AModel answer
Explicitly pass the 'encoding' parameter to open() (e.g., encoding='latin-1' or 'utf-8') rather than relying on the platform-dependent default — reading a file with the WRONG encoding raises a UnicodeDecodeError (for incompatible byte sequences) or silently produces GARBLED text (for compatible-but-wrong encodings that don't error).
try:
with open("legacy_data.txt", encoding="utf-8") as f:
content = f.read()
except UnicodeDecodeError:
with open("legacy_data.txt", encoding="latin-1") as f: # fallback encoding
content = f.read()Real-world example
Reading a legacy data file of unknown or non-UTF-8 encoding without crashing or silently corrupting non-ASCII characters.
Likely follow-ups
- Why does Python's open() NOT default to UTF-8 consistently across all platforms in older versions, and how does PEP 686 address this?
Related topics