python - populate table where each column comes from a different line of a text file -
I have a txt file where some lines contain strings and some other rows have a value. According to the values "related" are the last line. For example:
+ aaa '+' bbb '* value 1 * value 2 +' ccc '* value 3 +' ddd '
etc. . I am trying to create a table where the first column is wired and in the second column there are rows in which there are values. My problem is that if I consider the value of the string, then the string and value (list) must be on the same line. If there is no related value of the string, then I want to put it in the same line with NULL. Something like this:
Column 1 | Column 2 ----------------------------- + 'aaa' | Tap + 'BBB' | [* Value1, * value2] + 'ccc' | [* Value 3] + 'Deed' | NULL etc.
I tried to do something like this:
import sqlite3db = sqlite3.connect ('mydatabase.db') cur = db.cursor ('Myfile.txt') as opened (): ():. () '' For line for f.readlines () in line.startswith ('+'). Include in cur.execute ("mytable VALUES (?))", If line.startswith ('*'): cur.execute (include "mytable VALUES (?))", Line db.commit () db . ()
But obviously this is not right because the minetable takes two values.
You can not combine the same values as soon as you find them. At least you should just enter a row with the mystrings
column, and then when you find the myvalues
, update but as you have a string It can be more value than it is, it is so easy to store keys and values and to put a single:
import sqlite3 def createtable (dbname): db = sqlite3 .connect (dbname) ) Cur = db.cursor () cur.execute ('mystrings text, myvalues text') cur.close () db.close () def dropdb (dbname): db = sqlite3.connect (Dbname) ) Cur = db.cursor () cur.execute ('DROP table mytable ') Cur.close () db.close () def insert (cur, key, val): if the key is none: if len (val) == 0: value = none alif lane (wal) == 1 : Value = val [0] and: value = str (wal) # print "INSERT", key, value cur.execute ("insert in mytable values def trt (filename, dbname): key = none val = None db = sqlite3.connect (dbname) cur = db.cursor () Try: In the form of open (file name) as f: For line in f: i f line.startswith ('+'): If the key is not any: if len (val) == 0: value = None elif len (val) == 1: value = val [0] and: value = If the val is not any: [...: 1] key = line [: - 1] val = [] and: print "value", line [ : -: 1] Print "First value before string: ignore" and: val.append (line [: - 1]) Finally insert (CR, Key, Val) Finally: cur.close () db.commit () Db.close () createdb ('Mydatabase.db') trt ('myfile.txt', 'mydatabase.db')
Comments
Post a Comment