Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy CSV import (into SQLite)?

I would like to load CSV file into SQLite coded using SQLAlchemy (to fit other code).

The command line load looks like this:

create table MYTABLE (...);
.separator ','
.import myfile.csv MYTABLE

(Avoiding per row INSERTs) Is there an equivalent SQLAlchemy operation?

Thanks

like image 762
gliptak Avatar asked Mar 01 '26 14:03

gliptak


1 Answers

The .import command is part of the CLI and not part of the SQLite syntax.

If you want to import the content of the CSV file you can use the python's csv reader and using SQLAlchemy to insert every row (from the CSV) to the database:

>>> import csv
>>> with open('myfile.csv', 'rb') as csvfile:
...     tbl_reader = csv.reader(csvfile, delimiter=',')
...     for row in tbl_reader:
...         mytbl.insert().values(id=row[0], name=row[1], content=row[2])
like image 124
Dekel Avatar answered Mar 03 '26 03:03

Dekel