python3-批量csv转excel

我原来自己写过,我TM竟然忘记了…折腾半天.

"""
pandans  批量 csv文件转xls  行去重
"""
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:
        try:
            file_dir = os.path.join(root, item)
            # 输出文件的绝对路径.

            frame = pd.read_csv(file_dir, engine='c', encoding="unicode_escape", error_bad_lines=False, delimiter="\r")
            # 先读取文件
            data = frame.drop_duplicates(subset=None, keep='first', inplace=False)
            # 行去重,保留第一次重复行的数据.

            # 调整文件存储路径---------------------------------------------
            file_name = "".join(file_dir.split("\\")[-1])
            file_abPath = file_dir.replace("CSV", "Excel").replace(file_name, "")
            # 保留现有的路径.(这是我自己的路径)

            if not os.path.exists(file_abPath):
                os.makedirs(file_abPath)
            filename_file = file_name.replace("csv", "xls")
            # 将文件名改成xls
            
            if not os.path.exists(file_abPath + filename_file):
                data.to_excel(file_abPath + filename_file, encoding='utf-8-sig', index=None)
                # 写入到xls 文件中.

                print(file_abPath + filename_file, "完成")
            else:
                print(file_abPath + filename_file, "之前已经完成了")
        except Exception:
            pass

后缀一定要这个.xls不要忘记了.

欢迎补充…

你可能感兴趣的:(python3-批量csv转excel)