Shmoe Shmoe - 6 months ago 38
MySQL Question

Saving data from MySQL table to a text file with Python

So I have a mysql table and I am trying to take each element from one of the fields of the table. The field and table are both called "keywords". In the field there are many different random words and I am trying to take all of those and save them to a text file. Any help on how to implement this would be great, here is what I have so far.

#!/usr/bin/env python
import MySQLdb


db = MySQLdb.connect(host="", user="", passwd="", db="")
cursor = db.cursor()
sql = """SELECT DISTINCT keywords FROM keywords"""
cursor.execute(sql)
cursor.fetchall()
db.close()

for s in sql:
tweets = open("keywords.txt", "w")


What I was thinking is to turn what sql fetches into a list if possible and write that to the file. But I am open to any suggestions, thanks.

mvp mvp
Answer

Something like this should work:

import MySQLdb

db = MySQLdb.connect(host="", user="", passwd="", db="")
cursor = db.cursor()
sql = """SELECT DISTINCT keywords FROM keywords"""
tweets = open("keywords.txt", "w")
cursor.execute(sql)
for row in cursor:
   print>>tweets, row[0]
tweets.close()
db.close()