用Python把csv文件批量修改编码为UTF-8格式并转为Excel格式

有时候用excel打开一个csv文件,中文全部显示乱码。然后手动用notepad++打开,修改编码为utf-8并保存后,再用excel打开显示正常。

使用Python通过很少代码就能将上面过程自动化。

导入3个模块

python 复制代码
import pandas as pd  
import os 
import chardet

chardet 模块用于得到文件的编码格式,pandas 按照这个格式读取,然后保存为xlsx格式。

获取filename文件的编码格式

python 复制代码
def get_encoding(filename):
    """
    返回文件编码格式
    """
    with open(filename,'rb') as f:
        return chardet.detect(f.read())['encoding']

文件转码处理

保存为utf-8编码xlsx格式文件,支持csv, xls, xlsx 格式的文件乱码处理。需要注意,如果读入文件为csv格式,保存时要使用xlsx格式:

python 复制代码
def to_utf8(filename):
    """
    保存为 to_utf-8
    """
    encoding = get_encoding(filename)
    ext = os.path.splitext(filename)
    if ext[1] =='.csv':
        if 'gb' in encoding or 'GB' in encoding:
            df = pd.read_csv(filename,engine='python',encoding='GBK')
        else:
            df = pd.read_csv(filename,engine='python',encoding='utf-8')
        df.to_excel(ext[0]+'.xlsx')
    elif ext[1]=='.xls' or ext[1] == '.xlsx':
        if 'gb' in encoding or 'GB' in encoding:
            df = pd.read_excel(filename,encoding='GBK')
        else:
            df = pd.read_excel(filename,encoding='utf-8')
        df.to_excel(filename)
    else:
        print('only support csv, xls, xlsx format')

批量转换

上面函数实现单个文件转化,下面batch_to_utf8 实现目录 path 下所有后缀为ext_name文件的批量乱码转化:

python 复制代码
def batch_to_utf8(path,ext_name='csv'):
    """
    path下,后缀为 ext_name的乱码文件,批量转化为可读文件
    """
    for file in os.listdir(path):
        if os.path.splitext(file)[1]=='.'+ext_name:
            to_utf8(os.path.join(path,file))

使用

python 复制代码
if __name__ == '__main__':
  batch_to_utf8('.') # 对当前目录下的所有csv文件保存为xlsx格式,utf-8编码的文件
相关推荐
難釋懷4 分钟前
Nginx本地缓存
nginx·spring·缓存
MarkHD5 分钟前
从“能跑”到“好用”:Python脚本监控与告警实战(邮件/钉钉/企业微信)
python·钉钉·企业微信
徒 花14 分钟前
Python知识学习03
开发语言·python·学习
wjcroom18 分钟前
电子python模拟出的一个完美风暴
开发语言·python·数学建模·物理学
极创信息19 分钟前
不同开发语言程序如何做信创适配认证?完整流程与评价指标有哪些
java·c语言·开发语言·python·php·ruby·hibernate
清水白石00822 分钟前
Python 日志采集到数据仓库 ETL 流程设计实战:从基础语法到生产级可靠运维
数据仓库·python·etl
威联通网络存储24 分钟前
云原生容器底座:Kubernetes 持久化存储与 CSI 架构解析
python·云原生·架构·kubernetes
Thomas.Sir24 分钟前
第6节:Function Calling深度剖析
人工智能·python·ai·functioncalling
xinixini26 分钟前
2026年马年日历模板大全 可编辑Excel/Word/PSD/PDF素材合集
pdf·word·excel·日历
洛阳吕工27 分钟前
【Python 教程】无人机 MAVLink 通信完整实战:连接飞控、接收数据与发送指令
开发语言·python·无人机