Is there any way to transform this text file:
into that:
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))

