python读取csv文件出现‘\ufeff’乱码的解决方法

1、使用python中的csv模块读取文件的时候使用encoding='utf-8'解码,会在读取了列表的一个位出现‘‘\ufeff’’,代码如下:

import csv

def csv_reader():
    with open('2.csv','r',encoding='utf-8') as f:
        reader=csv.reader(f)
        return list(reader)

list1=csv_reader()
print(list1)
#输出结果
[['\ufeff2', '3'], ['3', '4'], ['4', '5'], ['5', '6'], ['6', '7'], ['7', '8'], ['8', '9'], 
['9', '10'],['10', '11'], ['11', '12'], ['12', '13'], ['13', '14'], ['14', '15']]

2、要去掉这个字符,只需要在读取的时候使用encoding='utf-8-sig'格式就好,代码如下:

import csv

def csv_reader():
    with open('2.csv','r',encoding='utf-8-sig') as f:
        reader=csv.reader(f)
        return list(reader)

list1=csv_reader()
print(list1)
#输出结果
[['2', '3'], ['3', '4'], ['4', '5'], ['5', '6'], ['6', '7'], ['7', '8'], ['8', '9'], ['9', '10'], ['10', '11'], ['11', '12'], ['12', '13'], ['13', '14'], ['14', '15']]

你可能感兴趣的:(python读取csv文件出现‘\ufeff’乱码的解决方法)