![](/img/trans.png)
[英]How to save output in .csv after every loop without overwriting in Pandas?
[英]How save an string output after a for loop in python with pandas and csv modules?
我有以下for循環:
for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
如何轉儲標題並將其鏈接到已格式化的.csv文件中?
您應該使用python CSV模塊。 在此處查找更多信息: 用Python將字符串列表寫入Excel CSV文件 。
這是您的問題的示例:
import csv
results = []
# your code... also add this to your for loop.
results.append([title, link])
csv_file = open("csv_file.csv",'wb')
wr = csv.writer(csv_file)
for row in results:
wr.writerow(row)
像這樣( 文檔 ):
...
doc_path = "path/to/doc.csv" # must exist, first folder on the place
# where you are running the script!
with open(doc_path, 'a') as doc:
for entry in titles:
title = entry.xpath("a/text()").extract()
link = entry.xpath("a/@href").extract()
print(title, link)
doc.write(str(title)+','+str(link)+'\n')
使用csv編寫器 。
基本用法:
import csv
with open('file.csv') as f:
writer = csv.writer(f)
writer.writerow(["title", "link"])
result = []
for titles in titles:
title = titles.xpath("a/text()").extract()
link = titles.xpath("a/@href").extract()
print(title, link)
result += [title + ',' + link + '\n']
with open("result.csv" "w+") as f:
f.writelines(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.