[Tutor] make a sqlite3 database from an ordinary text file

Manprit Singh manpritsinghece at gmail.com
Sun Jun 19 13:11:43 EDT 2022


Dear Sir,

I was trying to make a sqlite3 data base from an ordinary text file named
abcd.txt on my computer. it has data as given below in the form of 2
columns

Time  Pieces
1       10
2       15
3       25
4       31
5       40
6       45
7       53
8       54
9       65
10      75

Below given is the code that makes  sqlite3 database work.db, with a table
named
workdata, which will be having 2 columns Time & Pieces . The code lateron
fetches all data from the table.

import sqlite3

def data_generator(workfile):
    with open(workfile) as obj:
        obj.readline()
        for line in obj:
            yield tuple(line.split())


con = sqlite3.connect("work.db")
cur = con.cursor()
cur.execute("create table workdata(Time INT, Pieces INT)")
cur.executemany("insert into workdata values (?, ?)",
data_generator("abcd.txt"))
con.commit()
cur.execute("select Time, Pieces from workdata")
print(cur.fetchall())
cur.close()
con.close()

In this example i am using generator function for iterator to be used in
executemany(). I will not prefer a list comprehension in this case as a
file may contain a large number of rows .

Is there any better way to do this task ? Kindly suggest.

Regards
Manprit Singh


More information about the Tutor mailing list