Python在实际工作中的运用-通用格式CSV文件自动转换XLSX

继续上篇《Python在实际工作中的运用-CSV无损转XLSX的几个方法》我们虽然对特定格式的CSV实现了快速转换XLSX的目标,但是在运行Py脚本前,还是需要编辑表格创建脚本和数据插入脚本,自动化程度很低,实用性不强,为减少人工提高效率,实现输入CSV文件路径即可自动适配完成转换。现将改进后的脚本发出来,供大家共同交流学习。

脚本说明:

1、本脚本适合字段之间用空格分隔或者用逗号分隔的CSV文本

2、只需将CSV文件路径(含文件名和扩展名)设置到file_path_name变量即可

3、SQlite是中间库,本脚本在执行转换前会自动删除重建。

4、转换的XLSX文件,字段名是自动命名的,请自行修改为自己的表头。

python 复制代码
import os
import sqlite3
import re
import time
import pandas as pd
from pathlib import Path

# 公共变量
# 待转换的CSV文件【必填】
file_path_name = f'{os.path.dirname(__file__)}/待转换的CSV文件.csv'

# 首行是否标题true是false否(默认为否)
isheader = False
# 设置字段之间的分割符号,默认是空格
delimiter = " "
# 获取入口文件目录
file_dirname = os.path.dirname(file_path_name)
# 获取入口文件名(不带扩展名)
file_name = Path(file_path_name).stem

# 删除重建数据库
dbfile_path_name = f'{file_dirname}/{file_name}.db'
if os.path.exists(dbfile_path_name):
    os.remove(dbfile_path_name)
    # 连接到 SQLite 数据库(如果数据库文件不存在,会自动创建一个新的数据库文件)
    conn = sqlite3.connect(dbfile_path_name)
else:
    conn = sqlite3.connect(dbfile_path_name)

cursor = conn.cursor()
sql = f"select name from sqlite_master where name='{file_name}';"
cursor.execute(sql)

# 创建数据表
def CreateTB(conn, header_name = None):
    cursor = conn.cursor()
    # fetchone逐行获取查询结果,如果没有结果返回则判断表未创建
    if not bool(cursor.fetchone()):
        with open(file_path_name,'r',encoding='utf-8') as file:
            # 获取字段个数
            line = file.readline()
            if delimiter == " ":
                line = re.sub(r'\s+',',',line)

            if re.findall('^,',line):
                line = re.sub('^,','',line)

            if re.findall(',$',line):
                line = re.sub(',$','',line)

            # 将整理好的文本分割成字段,并获得字段数
            line_split = line.split(',')
            sql = ""
            if isheader:
                for i in range(len(line_split)):
                    sql += f",{line_split[i]} TEXT NOT NULL"
                    #index_name = line_split[index_num]
                    header_name += f"{line_split[i]},"

                    if i == len(line_split) - 1:
                        header_name = re.sub(',$','',header_name)
            else:
                for i in range(len(line_split)):
                    sql += f",字段名{i} TEXT NOT NULL"
                    #index_name = f"字段名{index_num}"
                    header_name += f"字段名{i},"

                    if i == len(line_split) - 1:
                        header_name = re.sub(',$','',header_name)

            sql = f"CREATE TABLE IF NOT EXISTS {file_name}(id INTEGER PRIMARY KEY{sql});"

            cursor.execute(sql)
            #sql = f"CREATE UNIQUE INDEX IF NOT EXISTS tableindex ON {file_name} ({index_name});"
            #cursor.execute(sql)
            # 提交更改
            conn.commit()
            return header_name

# 调用创建数据表函数
header = CreateTB(conn,"")

with open(file_path_name,'r',encoding='utf-8') as file:
    lines = file.readlines()
    rownum = len(lines)

    i=0
    cursor.execute('BEGIN TRANSACTION')
    start_time = time.time()
    for line in lines:
        # 这里用到正则表达式对数据中存在的多个空格以及数据行前后逗号进行处理
        if delimiter == " ":
            line = re.sub(r'\s+',',',line)

        if re.findall('^,',line):
            line = re.sub('^,','',line)

        if re.findall(',$',line):
            line = re.sub(',$','',line)

        # 对整理完的文本,用逗号进行分割
        line_split = line.split(',')

        # 组装insert插入记录
        fieldsValue = ""
        for j in range(len(line_split)):
            fieldsValue += f"'{line_split[j]}',"
            if j == len(line_split) - 1:
                fieldsValue = re.sub(',$','',fieldsValue)

        try:
            sql = f"INSERT OR ignore INTO {file_name}({header}) VALUES ({fieldsValue});"
            cursor.execute(sql)
        except Exception as e:
            #conn.rollback()
            print(e)

        # 对操作进行计数
        i=i+1
        if i == rownum:
            conn.commit()

            # 在这里将导入的待转换CSV文件数据经过SQLite数据库转化为Excel表导出
            df = pd.read_sql_query(f'select * from {file_name}',conn)
            df.to_excel(f'{file_dirname}/{file_name}.xlsx',index=False)

# 输出执行结果
end_time = time.time()
print(f'共转换{i}行,操作完毕,执行时间:{end_time-start_time}秒')
相关推荐
二十雨辰1 天前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码1 天前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
前端摸鱼匠1 天前
YOLOv8 环境配置全攻略:Python、PyTorch 与 CUDA 的和谐共生
人工智能·pytorch·python·yolo·目标检测
WangYaolove13141 天前
基于python的在线水果销售系统(源码+文档)
python·mysql·django·毕业设计·源码
AALoveTouch1 天前
大麦网协议分析
javascript·python
ZH15455891311 天前
Flutter for OpenHarmony Python学习助手实战:自动化脚本开发的实现
python·学习·flutter
xcLeigh1 天前
Python入门:Python3 requests模块全面学习教程
开发语言·python·学习·模块·python3·requests
xcLeigh1 天前
Python入门:Python3 statistics模块全面学习教程
开发语言·python·学习·模块·python3·statistics
YongCheng_Liang1 天前
从零开始学 Python:自动化 / 运维开发实战(核心库 + 3 大实战场景)
python·自动化·运维开发
鸽芷咕1 天前
为什么越来越多开发者转向 CANN 仓库中的 Python 自动化方案?
python·microsoft·自动化·cann