How do I choose and specify a text encoding when opening a file in Python?
Quick answer
Pass the encoding you know to Python’s open() call, for example open("sample.txt", "r", encoding="utf-8"). If you do not know the file’s encoding, do not assume Python can identify it reliably. Check how the file was created, look for documentation or an export setting, and test a suitable candidate on a copy while inspecting the resulting text.
The question, the details, the next step.
A practical checklist
Check the file’s creator, export settings, or documentation for an encoding.
Pass the known encoding explicitly with
encoding=...when opening text.If it is unknown, treat each candidate as an assumption, not a confirmed identification.
Inspect a read-only preview, including characters you expect to appear.
Record the chosen encoding, your reason, and what remains uncertain.
A few more useful answers
Why specify an encoding if my script already works on my computer?
Without an explicit encoding, Python uses a platform-dependent one, so behavior can vary across environments. Specifying the intended encoding makes that choice visible. [S1]
Does a readable preview prove that I picked the right encoding?
No. It can help assess a candidate, but a readable result alone does not establish how the file was originally encoded.
What if the file’s creator cannot confirm the encoding?
Record that uncertainty, inspect a copy using candidates supported by what you know about the file, and avoid presenting a tested guess as confirmed.
Sources
References used for this guide.
- [S1] Python Library Reference: open() docs.python.org · Checked
