文本数据格式转换备份

概述

一些文本格式转换代码,个人做一下备份。

ipynb转py格式

python 复制代码
import nbformat
from nbconvert import PythonExporter

# 读取 Jupyter notebook 文件
notebook_filename = 'Builddata.ipynb'  # 替换为你的 .ipynb 文件路径
with open(notebook_filename, 'r', encoding='utf-8') as notebook_file:
    notebook_content = nbformat.read(notebook_file, as_version=4)

# 使用 PythonExporter 将 notebook 转换为 Python 脚本
python_exporter = PythonExporter()
python_code, _ = python_exporter.from_notebook_node(notebook_content)

# 将 Python 代码写入 .py 文件
python_filename = notebook_filename.replace('.ipynb', '.py')
with open(python_filename, 'w', encoding='utf-8') as python_file:
    python_file.write(python_code)

print(f'Notebook converted to Python script: {python_filename}')

CSV格式转数据库db格式

python 复制代码
import sqlite3
import csv

# 你的CSV文件路径
csv_file = '202103_LD.csv'

# 转成SQLite数据库文件路径
db_file = '202103_LD.db'

# 连接SQLite数据库(如果数据库文件不存在,它会被自动创建)
conn = sqlite3.connect(db_file)
cursor = conn.cursor()

# 读取CSV文件并获取列名
with open(csv_file, mode='r', newline='', encoding='utf-8') as file:
    reader = csv.reader(file)
    headers = next(reader)  # 获取第一行(标签行)

    # 动态创建SQL表语句 data为表名
    columns = ', '.join([f"{header} TEXT" for header in headers])
    create_table_sql = f"CREATE TABLE IF NOT EXISTS data ({columns})"
    cursor.execute(create_table_sql)

    # 插入数据
    for row in reader:
        placeholders = ', '.join(['?' for _ in headers])
        insert_sql = f"INSERT INTO data ({', '.join(headers)}) VALUES ({placeholders})"
        cursor.execute(insert_sql, row)

# 提交事务并关闭连接
conn.commit()
conn.close()

print(f"数据成功从CSV文件导入到数据库 {db_file} 中!")

CSV格式转json格式

python 复制代码
import csv
import json

csv_file = 'data.csv'
json_file = 'data.json'

# 读取CSV文件
with open(csv_file, mode='r', newline='', encoding='utf-8') as csvf:
    reader = csv.DictReader(csvf)
    data = [row for row in reader]

# 写入JSON文件
with open(json_file, 'w', encoding='utf-8') as jsonf:
    json.dump(data, jsonf, ensure_ascii=False, indent=4)

json格式转CSV格式

python 复制代码
import json
import csv

json_file = 'data.json'
csv_file = 'data.csv'

# 读取JSON文件
with open(json_file, 'r', encoding='utf-8') as jf:
    data = json.load(jf)

# 写入CSV文件
with open(csv_file, mode='w', newline='', encoding='utf-8') as cf:
    writer = csv.DictWriter(cf, fieldnames=data[0].keys())
    writer.writeheader()
    writer.writerows(data)
相关推荐
zyseo86 小时前
谷歌SEO 准首页词挖掘脚本:找出排在第 8-20 名的隐藏流量
大数据·数据库·人工智能
xiaogai_gai7 小时前
仅查询策略实战:从金蝶云·星空旗舰版定时拉取收料通知单
大数据·数据库·python
数据工匠老o8 小时前
异构数据库DDL同步:260条链路的结构变更自动适配方案
数据库·架构
这个DBA有点耶9 小时前
银行业市占率最高的国产数据库是谁?先搞清楚“市占率”的四种口径
数据库·程序员·架构
用户6279947182629 小时前
南大通用GBase 8a之基于审计日志的冷温热数据分析
数据库
数据库小学妹10 小时前
数据库运维五级成熟度:监控、备份、高可用怎么串起来
运维·数据库·监控
一个天蝎座的程序猿10 小时前
为了给报表提速,我把金仓KES的列存储折腾了个遍:聊聊KES的技术能力
数据库
飞越未来云城的霓虹飞猪10 小时前
AI 数据库地图:从 PostgreSQL 到向量数据库,一次看懂 AI 时代的数据底座
数据库
不像程序员的程序媛10 小时前
导出mysql数据结构
数据库·mysql
GlobalTradercrb10 小时前
独立站SEO先写博客还是先优化产品页?看站点阶段
数据库·人工智能·google·pdf·go·seo