学习pandas遇到的坑(一)

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)
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值