Question

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()
Was it helpful?

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")

OTHER TIPS

Modules like pymysql conform to the Python DB API. The cursor's fetchall() method returns a list of tuples. Each tuple represents a single row from the database query. Converting this to a string probably doesn't give you what you want:

>>> str((1, ))
'(1,)'

The writerow method expects to be given a sequence and each element of the sequence is output as a value in the row, with appropriate representation and separators according to the format chosen.

You current logic loops over all the rows returned by your DB query.Each time around the loop it adds another (probably incorrect) value to a list, opens a file for writing, and writes out the current list. Since each iteration creates a new file you will only see what's written in the last iteration.

Here's code that might do what you want.

import csv

data = [("first",), ("second",), ("Third",)]
list = []

file = open('file.csv', 'wb')
writer = csv.writer(file)
for row in data :
    writer.writerow(row)
file.close()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top