2

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#

3
  • 1
    What is your separator and which are the desired values in the example? Commented Feb 17, 2015 at 18:42
  • unrelated but you can just iterate over f Commented Feb 17, 2015 at 18:44
  • Have you tried line.split('<=>')? Commented Feb 17, 2015 at 18:44

1 Answer 1

2

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#'
Sign up to request clarification or add additional context in comments.

1 Comment

Hi! Really thanks for your answer. I am not able to test it now but tomorrow morning ( Spain here ) will. Will ofc update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.