用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 小时前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
电脑能手5 小时前
如何远程访问在WSL运行的Jupyter Notebook
ide·python·jupyter
Edward-tan6 小时前
CCPD 车牌数据集提取标注,并转为标准 YOLO 格式
python
老胖闲聊6 小时前
Python I/O 库【输入输出】全面详解
开发语言·python
张小洛6 小时前
Spring AOP 是如何生效的(入口源码级解析)?
java·后端·spring
倔强青铜三6 小时前
苦练Python第18天:Python异常处理锦囊
人工智能·python·面试
倔强青铜三6 小时前
苦练Python第17天:你必须掌握的Python内置函数
人工智能·python·面试
迷路爸爸1807 小时前
让 VSCode 调试器像 PyCharm 一样显示 Tensor Shape、变量形状、变量长度、维度信息
ide·vscode·python·pycharm·debug·调试
追风少年浪子彦7 小时前
mapstruct与lombok冲突原因及解决方案
java·spring boot·spring·spring cloud
军军君017 小时前
基于Springboot+UniApp+Ai实现模拟面试小工具四:后端项目基础框架搭建下
spring boot·spring·面试·elementui·typescript·uni-app·mybatis