通过Python将数据合并到SQLite数据库中

2024-05-14 17:03:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经成功地将多个csv文件(包含在一个文件夹中)导入到一个SQLite数据库中,这要归功于我之前收到的非常有用的反馈 question on this forum。在

A16_B1_T5A16_B1_T6包含来自同一传感器的数据,用于测量温度和湿度。然而,这些数据是在一年中的不同时间收集的,因此它们总是有很大的重叠(即T5可能表示2015年4月至10月收集的数据,而T6可能表示2015年7月至12月收集的数据)。在

我现在正在尝试将两个或多个表(最初对应于单独的csv文件)合并为一个。对于参考示例,A16_B1_T5和A16_B1_T6应合并为A16_B1_T(或A16_B1_TT)。这意味着追加以及覆盖/删除重复数据。在

有什么建议吗?将csv批量导入sqlite的原始工作代码如下:

import csv
import sqlite3
import glob
import os

def do_directory(dirname, db):
    for filename in glob.glob(os.path.join(dirname, '*.csv')):
        do_file(filename, db)

def do_file(filename, db):
        with open(filename) as f:
            with db:
                data = csv.DictReader(f)
                cols = data.fieldnames
                table=os.path.splitext(os.path.basename(filename))[0]

                sql = 'drop table if exists "{}"'.format(table)
                db.execute(sql)

                sql = 'create table "{table}" ( {cols} )'.format(
                    table=table,
                    cols=','.join('"{}"'.format(col) for col in cols))
                db.execute(sql)

                sql = 'insert into "{table}" values ( {vals} )'.format(
                    table=table,
                    vals=','.join('?' for col in cols))
                db.executemany(sql, (list(map(row.get, cols)) for row in data))

    if __name__ == '__main__':
        connection = sqlite3.connect('C:/ROAST/3_ANALYSIS/03_SQL-PY/primo.db')
do_directory('C:/ROAST/3_ANALYSIS/03_SQL-PY\A08_csv',connection)

Tags: csv数据inimportformatfordbsql

热门问题