python - how to insert the data from csv file into sqlite db? -
there csv file in format.
x1 0 1 3 6 x2 4 9 4 5 x3 8 6 7 1
i want insert database 3 fields "x1","x2","x3" following data.
x1|x2|x3 0|4|8 1|9|6 3|10|7 6|5|1
i think have transform data when read csv file.
import sqlite3 db="test.sqlite" con = sqlite3.connect(db) cur = con.cursor() dat=open("data","r") id,line in enumerate(dat.readlines()): ? con.executemany('insert test values(?,?,?)', value)
how right format of value here?
transpose data zip(*rows)
, remove first line , insert .executemany()
call:
import csv import sqlite3 open('data', 'r', newline='') infh: rows = list(csv.reader(infh)) columns = zip(*rows) next(columns, none) # skip first column sqlite3.connect('test.sqlite') conn: cursor = conn.cursor() cursor.executemany('insert test values (?, ?, ?)', columns)
Comments
Post a Comment