在python中读取数据库并写入文件

在python中读取数据库并写入文件,python,mysql,Python,Mysql,我有一个到mysql数据库的连接,并用它进行查询,但我需要它们立即写入文件,这样做的简单方法是什么 conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb") cursor = conn.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT * FROM books") ..您可以使用Python附带的本机文件编写器来完成此操作。下面是您将如何做到

我有一个到mysql数据库的连接,并用它进行查询,但我需要它们立即写入文件,这样做的简单方法是什么

conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM books")

..

您可以使用Python附带的本机文件编写器来完成此操作。下面是您将如何做到这一点的示例:

with open('/path/to/file.txt', 'w') as f:
    conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    result = cursor.execute("SELECT * FROM books")
    f.write(result)
提示:注意,如果文件已经存在,将文件模式设置为W将覆盖该文件

提示:文件路径必须相对于正在执行的python脚本


资源:

您可以使用上面的代码:(每行作为新行插入)

 conn = MySQLdb.connect(host="localhost",user="root",passwd="",db="mydb")
    cursor = conn.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("SELECT * FROM books")
    result_set = cursor.fetchall()    
    field_names = [val[0] for val in cursor.description]

with open('yourfile.txt', 'a') as f:
    for row in result_set:
       line = ','.join(row[field_name] for field_name in field_names)
       f.write(line)