背景:
学习python制作数据可视化时时,从世界银行(http://data.worldbank.org/indicator/)下载csv文件,读取csv内容时,发现文件头第一行会有乱码问题,经查阅原来是头部有codecs.BOM_UTF8(xefxbbxbf),以下简称BOM,这些内容在csv中看不出来。
经过:
1.不设置格式,直接读取(Windows下应该是gbk编码吧),
import csv
file_name = 'API_MS.MIL.TOTL.P1_DS2_en_csv_v2.csv' with open(file_name) as f: reader = csv.reader(f) head_row = next(reader) print(head_row)
开头出现乱码,结果如下:
['锘緿ata Source', 'World Development Indicators', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
2.设置utf-8格式读取:
import csv file_name = 'API_MS.MIL.TOTL.P1_DS2_en_csv_v2.csv' with open(file_name, encoding='utf-8') as f: reader = csv.reader(f) head_row = next(reader) print(head_row)
开头‘乱码’变为ufeff,显示如下:
['ufeffData Source', 'World Development Indicators', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
解决:
翻到一篇帖子(https://www.cnblogs.com/chongzi1990/p/8694883.html),只要把utf-8编码改成utf-8-sig即可,具体原因这篇帖子里有些到。
import csv file_name = 'API_MS.MIL.TOTL.P1_DS2_en_csv_v2.csv' with open(file_name, encoding='utf-8-sig') as f: reader = csv.reader(f) head_row = next(reader) print(head_row)
显示正常,得到了想要的内容:
['Data Source', 'World Development Indicators', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']
*期间尝试过其他方式,比如先读取csv内容,将头行存入新文件,再以‘rb'二进制方式读取,判断如果有BOM,则剔除掉,。。。很麻烦,还是直接制定utf-8-sig方法最简单。