How can I read a UTF-8 text file that may start with a byte-order mark?
Quick answer
For a local file that may begin with a UTF-8 byte-order mark (BOM), open it with encoding="utf-8-sig" if you want Python to skip that optional marker at the start. Ordinary encoding="utf-8" leaves an initial BOM as the first character, U+FEFF. To check for it after ordinary decoding, use text.startswith("\ufeff"). [S1]
The question, the details, the next step.
A practical checklist
Replace
[sample-file.txt]with the path to your local file.Choose
utf-8to retain a starting BOM as U+FEFF, orutf-8-sigto skip an optional BOM at the start.If checking with ordinary UTF-8, test
text.startswith("\ufeff").Interpret the check narrowly: it tests the first character, not the file’s encoding or every character in the text.
A few more useful answers
Does `utf-8-sig` remove U+FEFF wherever it appears in the file?
No. It skips the optional UTF-8 signature when it occurs at the start of the data; it is not a general cleanup operation for other positions. [S1]
Does a `False` result from `text.startswith("\ufeff")` prove the file is UTF-8?
No. It only means the decoded text does not begin with U+FEFF. This check does not establish the file’s encoding or detect arbitrary encoding errors. [S1]
Which option should I use if I want to check for the marker rather than skip it?
Read with encoding="utf-8", then test text.startswith("\ufeff"). Ordinary UTF-8 decoding leaves an initial BOM as U+FEFF. [S1]
Sources
References used for this guide.
- [S1] Python codecs: UTF-8 and UTF-8-with-signature docs.python.org · Checked
