Python › File I/O & Context Managers
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?
AdvancedAnswer
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.