Issue
I got this code from an another stackflow post and it works perfectly. But now i would like to direct the output to a text file as opposed to on the screen. How can i do it?
import mysql.connector
from tabulate import tabulate
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="testDB"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT emp_name, salary FROM emp_table")
myresult = mycursor.fetchall()
print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql'))
Solution
You can use sys.stdout
to log the output to a txt file.
Try:
import sys
with open('file.txt', 'w+') as sys.stdout:
import mysql.connector
from tabulate import tabulate
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="testDB"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT emp_name, salary FROM emp_table")
myresult = mycursor.fetchall()
print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql'))
Answered By - Minh-Long Luu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.