read_csv读取的csv文件编码格式的问题:
read_csv函数enconding参数的默认值是utf-8
而CSV是用UTF-8编码的,而EXCEL是ANSI编码。
这里顺便说一下xls与xlsx的区别,xls是excel2003及以前版本生成的文件格式。xlsx是excel2007及以后版本生成的文件格式
顺便说一下怎么创建一个utf-8编码的csv:
(1)新建一个excel修改后缀名 ×
(2)新建一个txt→打开txt→另存为→选择编码和修改后缀 ×
(3) 新建txt→修改后缀→用notepad++打开→转换编码 √
如果需要循环读取多个csv文件,而每个csv文件的编码都可能不一样,那么最好还是先把所有这些csv统一转为utf-8,再集中进行读取,转换文件的编码格式需要用到python自带的codecs模块
import codecs
def handleEncoding(original_file,newfile):
#newfile=original_file[0:original_file.rfind(.)]+'_copy.csv'
f=open(original_file,'rb+')
content=f.read()#读取文件内容,content为bytes类型,而非string类型
source_encoding='utf-8'
#####确定encoding类型
try:
content.decode('utf-8').encode('utf-8')
source_encoding='utf-8'
except:
try:
content.decode('gbk').encode('utf-8')
source_encoding='gbk'
except:
try:
content.decode('gb2312').encode('utf-8')
source_encoding='gb2312'
except:
try:
content.decode('gb18030').encode('utf-8')
source_encoding='gb18030'
except:
try:
content.decode('big5').encode('utf-8')
source_encoding='gb18030'
except:
content.decode('cp936').encode('utf-8')
source_encoding='cp936'
f.close()
#####按照确定的encoding读取文件内容,并另存为utf-8编码:
block_size=4096
with codecs.open(original_file,'r',source_encoding) as f:
with codecs.open(newfile,'w','utf-8') as f2:
while True:
content=f.read(block_size)
if not content:
break
f2.write(content)