rows from sql query need to write to a file as columns - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: rows from sql query need to write to a file as columns (/thread-35201.html) |
rows from sql query need to write to a file as columns - sjcsvatt - Oct-08-2021 I have a query that may have dynamic number of columns. I have include 2 columns for testing purpose. whenever they added fields to the table the number of columns in query may change. with present code, I am getting output like below (,1,0,6,5,,, ,',S,t,r,e,e,t, ,L,e,v,e,l, ,4,',) ----- (,1,1,4,5,,, ,',V,i,c,t,o,r,i,a, ,S,t,r,e,e,t,',) ------ (,1,2,2,2,,, ,',F,r,a,n,k,l,i,n, ,S,t,r,.,',) ----- *Expected output: 1065 Street Level 4 ----- 1145 Victoria Street ------- 1222 Franklin Str. ---- Quote:Python Code: RE: rows from sql query need to write to a file as columns - snippsat - Oct-08-2021 Use Code tags The problem is this,is not converting into tuple. >>> f_result= ','.join(str(s)) >>> f_result 'h,e,l,l,o, ,w,o,r,l,d'Bye your output so is input comma separated. 1065, Street Level 4Test,i make input like over each on new line. with open('test.txt') as f, open('test_file.txt', 'w') as wf: for line in f: line = line.strip().replace(', ', '\n') wf.write(f'{line}\n') wf.write('----------\n')
RE: rows from sql query need to write to a file as columns - sjcsvatt - Oct-08-2021 I will try and get back to you. RE: rows from sql query need to write to a file as columns - sjcsvatt - Oct-08-2021 I didn't understand your code, ... Where is the query out being passed to the for loop?? could you please elaborate? RE: rows from sql query need to write to a file as columns - sjcsvatt - Oct-08-2021 I tried like this: with open('test_file.txt','w') as wf: for i in qry_result: f_result= ''.join(str(i))##converting into tuple splitstring = f_result.strip().replace(', ', '\n') wf.write(f'{splitstring}\n') wf.write('----------'+"\n") output: (1065 'Street Level 4') ---------- (1145 'Victoria Street') ---------- (1222 'Franklin Str.') ---------- RE: rows from sql query need to write to a file as columns - sjcsvatt - Oct-08-2021 I don't want brackets and single quotes over the text value RE: rows from sql query need to write to a file as columns - snippsat - Oct-09-2021 (Oct-08-2021, 10:54 PM)sjcsvatt Wrote: I didn't understand your code, ... Where is the query out being passed to the for loop?? could you please elaborate?test.txt:
Quote:I don't want brackets and single quotes over the text valueShow a sample of how input qry_result look and what data type it is.By output it look something liker this. >>> s = ('1065', "'Street Level 4'") >>> # Clean up >>> s = ', '.join(s) >>> s "1065, 'Street Level 4'" >>> s.replace("'", '') '1065, Street Level 4' |