Part 08 / Topic 5 of 10
Encodings and UTF-8
A file stores bytes (numbers from 0 to 255). An encoding is the rule that turns text into bytes and back, like a codebook shared by the writer and the reader. UTF-8 can store every language (English, Hindi, Tamil, emoji) and is the standard on the web.
If you do not pass encoding, Python 3.13 and 3.14 use your system's locale encoding (a setting of your computer). On many Windows setups that is not UTF-8, so Hindi text or ₹ can break or show as garbage. Python 3.15 turns UTF-8 mode on by default (PEP 686), but your code may run on older versions too. Always write encoding="utf-8" for text files.
Tip: run your program with
python -X warn_default_encoding my_script.py. Python then prints anEncodingWarningfor everyopen()(orread_text/write_text) that is missingencoding=, so you can find and fix them.
Real-world example: a price list with ₹ and Hindi.
text = "चाय ₹10"
print(len(text)) # 7 characters (चाय is 3: च + ा + य)
print(len(text.encode("utf-8"))) # 15 bytes (each Hindi character and ₹ take 3 bytes)
with open("demo_menu.txt", "w", encoding="utf-8") as f:
f.write(text)
with open("demo_menu.txt", encoding="utf-8") as f:
print(f.read()) # चाय ₹10
🔍 Going deeper: a wrong encoding raises
UnicodeDecodeErrorwhen reading, or silently shows garbage (mojibake). CSV files saved by Excel often start with a hidden "BOM" mark; read them withencoding="utf-8-sig".
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.