在csv python中写入查询行

时间:2021-12-27 18:13:18

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

我正在写一个脚本来在csv文件中写入查询结果行。数据是电子邮件地址,如下所示:

email1@mail.com

email2@mail.com

email3@mail.com

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

现在,我的代码将我的结果写在csv文件中,如下所示:

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

('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'),

编辑:似乎我的查询给我括号之间的数据,如''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()

2 个解决方案

#1


2  

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

要获得更详细/更合适的解决方案,您必须向我们提供更多详细信息,例如:你的输入格式是什么样的,你希望你的输出文件是什么样的(实际数据,而不是抽象的“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:

编辑:如果您所做的只是每行编写一个电子邮件地址,那么您实际上并不是在使用CSV,也不需要该模块。这是我要做的:

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

#2


0  

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:

像pymysql这样的模块符合Python DB API。游标的fetchall()方法返回元组列表。每个元组代表数据库查询中的一行。将其转换为字符串可能无法满足您的需求:

>>> 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.

writerow方法期望给出一个序列,并且序列的每个元素作为行中的值输出,具有根据所选格式的适当表示和分隔符。

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

#1


2  

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

要获得更详细/更合适的解决方案,您必须向我们提供更多详细信息,例如:你的输入格式是什么样的,你希望你的输出文件是什么样的(实际数据,而不是抽象的“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:

编辑:如果您所做的只是每行编写一个电子邮件地址,那么您实际上并不是在使用CSV,也不需要该模块。这是我要做的:

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

#2


0  

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:

像pymysql这样的模块符合Python DB API。游标的fetchall()方法返回元组列表。每个元组代表数据库查询中的一行。将其转换为字符串可能无法满足您的需求:

>>> 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.

writerow方法期望给出一个序列,并且序列的每个元素作为行中的值输出,具有根据所选格式的适当表示和分隔符。

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