如何将Python执行MySQL查询的结果输出到文本文件?
实现将MySQL查询结果输出到文本文件的几种方法
下面提供三种实用的解决方案,无需大幅修改原有代码:
方法1:修改print语句,指定输出文件
直接利用Python print 函数的 file 参数,将输出定向到文件。使用with语句可以自动管理文件资源,避免手动关闭的麻烦:
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() # 以写入模式打开文件(不存在则创建,存在则覆盖),指定UTF-8编码避免乱码 with open('query_result.txt', 'w', encoding='utf-8') as f: print(tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql'), file=f)
方法2:先生成表格字符串,再写入文件
先将查询结果转换为表格字符串,再写入文件,这种方式更灵活,方便对输出内容做额外处理(比如添加注释、时间戳等):
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() # 生成格式化后的表格字符串 table_content = tabulate(myresult, headers=['EmpName', 'EmpSalary'], tablefmt='psql') # 写入文件 with open('query_result.txt', 'w', encoding='utf-8') as f: f.write(table_content)
方法3:命令行重定向输出(无需修改代码)
如果不想改动代码,可在运行脚本时通过命令行重定向输出到文件:
- 覆盖写入文件:
python your_script_name.py > query_result.txt
- 追加内容到文件(不覆盖原有内容):
python your_script_name.py >> query_result.txt
内容的提问来源于stack exchange,提问作者Pradeep Puri
相关产品推荐
相关产品推荐

