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

Alan Gauld alan.gauld at yahoo.co.uk
Mon Jun 20 07:07:48 EDT 2022


On 20/06/2022 01:59, Manprit Singh wrote:

> clear that the database table will have 2 columns, Column names of the
> sqlite3 table are to be picked from the  first line of the text file
> abcd.txt. (First column name will be Time, second column name will be
> Pieces ).
> See i know this can be done very easily using numpy and Pandas. But I am
> trying to do it with Core Python only.
> 
> cur.execute("create table workdata(? INT, ? INT)", ("Time", "Pieces"))
> 
> I just want to insert column names (where these column names are  read
> from text file abcd.txt 1st line)  using a question mark style
> placeholder. 

OK, Having shown how I would really do it, I'll now try to
answer the question for pure Python:

def get_data(open_file):
    for line in open_file:
        yield line.split()


# open the database/cursor here....

with open('data.txt') as inf:
    heads = inf.readline().split()
    cur.execute("create table DATA(? INT, ? INT)",heads)
    cur.executemany("insert into workdata values (?, ?)",get_data(inf))

cur.execute("select * from DATA")
for row in cur.fetchall():
    print(row)


Note, I didn't actually run this but I think it should be close.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list