Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Moving lines up into a file with python

Is there any way to transform this text file:

What I am getting

into that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The result I want

My code is:

query = "SELECT date_ FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query,(from_date,to_date))
for cursor in mycursor:
     file.write(f"{cursor[0]}\n")


query = "SELECT customer_surname FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query,(from_date,to_date))
for cursor in mycursor:
     file.write(f"\t\t{cursor[0]}\n")


query = "SELECT amount FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query,(from_date,to_date))
for cursor in mycursor:
       file.write(f"\t\t\t\t{cursor[0]}\n")

query = "SELECT description FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query,(from_date,to_date))
for cursor in mycursor:
     file.write(f"\t\t\t\t\t\t{cursor[0]}\n")



file.close()
os.system("notepad.exe BasicTextFile.txt")

>Solution :

You’re querying one field at a time from the same table with the same where rules, just query all at once

query = "SELECT date_, customer_surname, amount, description FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query, (from_date, to_date))
for row in mycursor:
    file.write("\t".join(row))

old answer

You need to save each query results in a list, then zip to get each row from all the columns, and write it

cols = []

query = "SELECT date_ FROM customers_payments7 WHERE date_ >= %s AND date_ <= %s"
mycursor.execute(query, (from_date, to_date))
cols.append([value for value, in mycursor])

# ...

for row in zip(*cols):
    file.write("\t".join(row))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading