Reputation: 55
I have been trying to split lines from a file and save that split data into variables without success.
My code is now like this:
cur = db.cursor()
query = """INSERT INTO xxxx (var1, var2) VALUES (%s, %s)"""
with open('data.txt') as f:
da = f.readlines()
for line in da:
values = (v1,v2)
cur.execute(query,values)
But it doesn't work as I want.
My request is if any of you can help me to get from data.txt
the values needed and saved to variables to be able to send them as a query to the database.
data.txt
has now this:
0013a200419e323b <=>€#356894040#XBEE#0#STR:XBee frame#BAT:1#
0013a200419e323b <=>€#356894040#XBEE#0#STR:XBee frame#BAT:1#
So var1
has to be equal to 0013a200419e323b
and var2
to <=>€#356894040#XBEE#0#STR:XBee frame#BAT:1#
Upvotes: 2
Views: 117
Reputation: 180391
you need to split once on white space:
with open('data.txt') as f:
for line in f: # can iterate over f, no need for readlines
values = line.split(None, 1) # splits on first whitespace only
cur.execute(query,values)
You will get a list containing the two substrings you want:
In [13]: s="0013a200419e323b <=>€#356894040#XBEE#0#STR:XBee frame#BAT:1#"
In [14]: s.split(None,1)
Out[14]: ['0013a200419e323b', '<=>\xe2\x82\xac#356894040#XBEE#0#STR:XBee frame#BAT:1#']
In [15]: var1,var2 = s.split(None,1)
In [16]: var1
Out[16]: '0013a200419e323b'
In [17]: var2
Out[17]: '<=>\xe2\x82\xac#356894040#XBEE#0#STR:XBee frame#BAT:1#'
Upvotes: 2