Python读取列名手动删除BOM示例代码(在Python中打开文件使用utf-8-sig和utf-8的区别)
def read_csv_to_dict(filename):
with open(filename, 'r', errors='ignore', encoding='gbk') as f:
reader = csv.DictReader(f)
fieldnames = [name.lstrip('\ufeff') for name in reader.fieldnames] # 删除列名前的BOM
print(fieldnames)
data_dict = defaultdict(list)
for row in reader:
if row[fieldnames[4]] != '': # 使用处理过的列名
data_dict[row[fieldnames[0]]].append((row[fieldnames[1]], round(float(row[fieldnames[4]]))))
return data_dict
参考: