0

I am reading data from file inputfile.txt:

inputfile.txt:

    sch,tab,"select no,name,place from test"
    sch1,tab1,"select no,name,place from test1"

file1 = open('inputfile.txt', 'r')
Lines = file1.readlines()
[sch,tab,query]=line.split(",")
print(query)

It is printing like :'select no'

My expected output is : 'select no,name,place from test'

how to print complete query instead of sub query.

2
  • Unless you are specifically asking about how to solve a cross-version compatibility problem (in which case your question should obviously describe that problem) you should not mix the python-2.7 and python-3.x tags. I have removed the former. Commented May 3, 2021 at 11:08
  • If your actual question is how to avoid splitting quoted strings, probably look into the csv module, which does exactly this. Commented May 3, 2021 at 11:09

4 Answers 4

2

Use csv module with quotechar='"'

Ex:

import csv

with open('inputfile.txt') as infile:
    reader = csv.reader(infile, quotechar='"')
    for line in reader:
        sch,tab,query =line
        print(query)

Output:

select no,name,place from test
select no,name,place from test1
Sign up to request clarification or add additional context in comments.

Comments

1

Split into 3 parts using second parameter to split()

[sch,tab,query]=line.split(",", 2)

Comments

0

If you split by , it will consider it from query as well.

You can split by select and use the last string as query check below example:

query = 'select ' + line.split('select')[-1]

or if your pattern is fix then you can do like this:

query = ','.join(line.split(',')[2:])

Comments

0

All the other answers are correct but from what I think you're trying to do, check out the shlex module on python.org: https://docs.python.org/3/library/shlex.html

Comments

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.