-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #14 from tmck-code/utf-8-sig
Utf 8 sig
- Loading branch information
Showing
2 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
34 changes: 34 additions & 0 deletions
34
articles/20230919_parsing_boms_in_python/20230919_parsing_boms_in_python.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# 20230919 Parsing BOMs in Python | ||
|
||
```python | ||
import csv, codecs | ||
|
||
CODECS = { | ||
"utf-8-sig": [codecs.BOM_UTF8], | ||
"utf-16": [ | ||
codecs.BOM_UTF16, | ||
codecs.BOM_UTF16_BE, | ||
codecs.BOM_UTF16_LE, | ||
] | ||
} | ||
|
||
def detect_encoding(fpath): | ||
with open(fpath, 'rb') as istream: | ||
data = istream.read(3) | ||
for encoding, boms in CODECS.items(): | ||
if any(data.startswith(bom) for bom in boms): | ||
return encoding | ||
return 'utf-8' | ||
|
||
def read(fpath): | ||
with open(fpath, 'r', encoding=detect_encoding(fpath)) as istream: | ||
yield from csv.DictReader(istream) | ||
``` | ||
|
||
```python | ||
# run here | ||
for i, row in enumerate(read('test.csv')): | ||
print(i, row) | ||
if i > 10: | ||
break | ||
``` |