Python read csv - BOM embedded into the first key
In Python 3, the built-in open
function is an alias for io.open
.
All you need to open a file encoded as UTF-8 with BOM:
open(path, newline='', encoding='utf-8-sig')
Example
import csv
...
with open(path, newline='', encoding='utf-8-sig') as csv_file:
reader = csv.DictReader(csv_file, dialect='excel')
for row in reader:
print(row['first_name'], row['last_name'])
You have to tell open that this is UTF-8 with BOM. I know that works with io.open:
import io
.
.
.
inputFile = io.open("test.csv", "r", encoding='utf-8-sig')
.
.
.
And you have to open the file in text mode, "r" instead of "rb".