Search code examples
pythoncsvpymysql

Write query rows in csv python


I'm wrinting a script to write query results rows in a csv file. The data is email adresses, like this :

email1@mail.com

email2@mail.com

email3@mail.com

For now, my code writes my results in the csv file like this :

('email1@mail.com'), ('email2@mail.com'), ('email3@mail.com'),

How can I use next lines instead of rows ?

EDIT : It seems that my query gives me data between brackets like ('email1@mail.com'),

Here is the code :

import pymysql
import csv

db = pymysql.connect(host="localhost", port=3306, user="foo", passwd="bar", db="db")
cursor = db.cursor()

query3 = """SELECT email FROM tmp"""


cursor.execute(query)

data = cursor.fetchall()
list = []

for row in data :
  value = str(row)
  list.append(value)    
  file = open('file.csv', 'wb')
  data = csv.writer(file)
  data.writerow(list)

cursor.close()
db.close()
file.close()

Solution

  • The following looks like it'd solve your problem:

    f = csv.writer(open("file.csv", "w"))
    for row in data:
        f.writerow([str(row)])
    

    For a more detailed/appropriate solution, you'll have to give us more details, e.g. what does your input format look like, and what do you want your output file to look like (actual data, not abstract "a, b, c").

    As a side note, do not call your variables list or file. Those names shadow the built-in list/file types.

    EDIT: If all you're doing is writing one e-mail address per line, you're not really doing CSV, nor do you need the module. Here's what I'd do:

    f = open("file.txt", "w")
    for i in email_addresses:
        f.write(i + "\n")