天宫鹤

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

参考:

在Python中打开文件使用utf-8-sig和utf-8的区别

posted on 2024-09-11 07:51  GoGrid  阅读(12)  评论(0编辑  收藏  举报

导航