将循环输出写入CSV列

时间:2014-02-27 20:08:25

标签: python csv

我有一个打印4个细节的for循环:

deats = soup.find_all('p')
    for n in deats:
        print n.text

输出为4行。

而不是打印,我想要做的是将每个'n'写入.csv中的不同列。显然,当我使用常规.write()时,它将它放在同一列中。换句话说,我如何将循环的每次迭代写入下一列?

4 个答案:

答案 0 :(得分:2)

您可以将csv行创建为循环(或使用列表推导)我将显示显式循环以便于阅读,您可以自己将其更改为单个列表理解行。

row = []
for n in deats:
  row.append(n)

现在您已准备好使用csv.Writer()

写入.csv文件的行

答案 1 :(得分:1)

extra_stuff = pie,cake,eat,too
some_file.write(",".join(n.text for n in deats)+"," + ",".join(str(s) for s in extra_stuff))

???那就是你要找的吗?

答案 2 :(得分:1)

嘿,试试这样:

import csv

csv_output = csv.writer(open("output.csv", "wb"))   # output.csv is the output file name!
csv_output.writerow(["Col1","Col2","Col3","Col4"]) # Setting first row with all column titles

temp = []
deats = soup.find_all('p')
for n in deats:
    temp.append(str(n.text))
csv_output.writerow(temp)

答案 3 :(得分:1)

您可以使用csv模块:

import csv
with open('output.csv', 'wb') as csvfile:
    opwriter = csv.writer(csvfile, delimiter=','
    opwriter.writerow([n.text for n in deats])