Home > Back-end >  Problem while trying to write elements from mysql into text file
Problem while trying to write elements from mysql into text file

Time:01-02

file = open("BasicTextFile.txt", "w")

query = "SELECT name, amount, description FROM customers_payments7777 GROUP BY customer_VAT"
mycursor.execute(query)
for row in mycursor:
    file.write(f"{row[0]}\t{row[1]}\t\t{row[2]}")
    file.write("\n")

file.close()

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

This is my code. It is getting some information from a table in MySQL and then it is writing it into a file. But the result I am getting is something like:

James   50.00            Hello
Nick            25.00

The result I want to get is something like:

James    50.00    Hello
Nick     25.00

CodePudding user response:

change line: file.write(f"{row[0]}\t{row[1]}\t\t{row[2]}")

to: file.write(f"{row[0]:10} {row[1]:7.2f} {row[2]:10}")

The first and third column wil have a length of 10 characters (:10), and the second column will be shown with max 7 characters, with 2 after the decimal .. (:7.2f).

If your text (or numbers) are larger then the space provided, the output will not be aligned, so you should choose the column widths to fit the longest text.

  • Related