将for循环输出写入CSV列

2024-10-01 11:37:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

输出为4条打印线。在

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


Tags: csvtextinforallfind细节write
3条回答

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

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

现在可以使用csv.Writer()

您可以使用csv模块进行此操作:

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

嘿,试着这样:

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)

相关问题 更多 >