python3-pandas-csv-xlsx-互相转换-行去重

csv转xlsx

import os

import pandas as pd

path = "绝对路径"

for root, dirs, files in os.walk(path):
    """
    应该是位置传参.
    root      为   path的路径.
    dirs      为   path路径下的所有目录.
    files     为   dirs目录下所有存在的文件
    """
    for item in files:
        if item.endswith(".csv"):
            #  获取绝对路径
            file_dir = os.path.join(root, item)
            try:
                # 读取文件内容
                csv_file = pd.read_csv(file_dir, low_memory=False, encoding='utf-8')

                # 行去重
                del_lines = csv_file.drop_duplicates()

                #  文件重命名
                xlsx_file_name = file_dir.replace(".csv", ".xlsx")

                # 当前文件不存在 才进行写入
                if not os.path.exists(xlsx_file_name):
                    # 文件写入
                    del_lines.to_excel(xlsx_file_name, index=False, encoding='gbk')

                if os.path.exists(xlsx_file_name):
                    print(xlsx_file_name, "完成")

            except Exception as e:
                print(file_dir, ValueError(e))
                pass

xlsx转csv 注意: pip install xlrd==1.2.0 这个一定要安装低版本的.

import os

import pandas as pd

path = "绝对路径"

for root, dirs, files in os.walk(path):
    """
    应该是位置传参.
    root      为   path的路径.
    dirs      为   path路径下的所有目录.
    files     为   dirs目录下所有存在的文件
    """
    for item in files:
        if item.endswith(".xlsx"):
            #  获取绝对路径
            file_dir = os.path.join(root, item)
            try:
                # 读取文件内容
                excel_file = pd.read_excel(file_dir)

                # 行去重
                del_lines = excel_file.drop_duplicates()

                #  文件重命名
                csv_file_name = file_dir.replace(".xlsx", ".csv")

                # 当前文件不存在 才进行写入
                if not os.path.exists(csv_file_name):
                    # 文件写入
                    del_lines.to_csv(csv_file_name, index=False, encoding='gbk')

                if os.path.exists(csv_file_name):
                    print(csv_file_name, "完成")

            except Exception as e:
                print(file_dir, ValueError(e))
                pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值