PyBot/db/Format_to_txt.py
2024-12-10 11:49:15 +08:00

46 lines
1.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import sqlite3
def read_sqlite_and_append_to_file(folder_path, output_file='./1.txt'):
"""
读取指定文件夹下所有SQLite数据库中的数据并将其按照“列名: 内容”的格式
追加到指定的文本文件中。
:param folder_path: 包含SQLite数据库的文件夹路径
:param output_file: 输出文件的路径,默认为'1.txt'
"""
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
if filename.endswith('.db'):
db_path = os.path.join(folder_path, filename)
# 连接到SQLite数据库
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# 获取所有表名
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = cursor.fetchall()
for table_name in tables:
table_name = table_name[0]
# 获取表的列名
cursor.execute(f"PRAGMA table_info({table_name});")
columns = cursor.fetchall()
column_names = [col[1] for col in columns]
# 查询表中的所有数据
cursor.execute(f"SELECT * FROM {table_name};")
rows = cursor.fetchall()
for row in rows:
# 将每一行的数据按照“列名: 内容”的格式写入文件
with open(output_file, 'a', encoding='utf-8') as file:
for col_name, value in zip(column_names, row):
file.write(f"{col_name}: {value}\n")
file.write("\n") # 每一行数据之间添加一个空行
# 关闭数据库连接
conn.close()
# 示例使用
read_sqlite_and_append_to_file('./db/')