目前,我正在使用Python 3执行数据抓取项目,并试图将已抓取的数据写入CSV文件。我目前的做法是:
import csv
outputFile = csv.writer(open('myFilepath', 'w'))
outputFile.writerow(['header1', 'header2'...])
for each in data:
scrapedData = scrap(each)
outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...])但是,该脚本完成后,CSV文件将为空。如果我只是跑:
import csv
outputFile = csv.writer(open('myFilepath', 'w'))
outputFile.writerow(['header1', 'header2'...])生成一个CSV文件,其中包含标题:
header1,header2,..例如,如果我只是在data中刮1:
outputFile.writerow(['header1', 'header2'...])
scrapedData = scrap(data[0])
outputFile.writerow([scrapedData.get('header1', 'header 1 NA'), ...])将创建一个CSV文件,包括data[0]的头文件和数据。
header1,header2,..
header1 data for data[0], header1 data for data[0]为什么是这种情况?
发布于 2018-08-03 23:34:49
使用w打开文件时,它会擦除以前的数据。
从医生那里 w:打开写文件,先截断文件
因此,在用w编写刮擦数据之后打开文件时,只需得到一个空白文件,然后将头写在文件头上,从而只看到标题。尝试将w替换为a。所以打开文件的新调用看起来就像
outputFile = csv.writer(open('myFilepath', 'a'))
您可以细化有关打开文件这里的模式的更多信息。
参考文献:如何附加到文件中?
DYZ评论后的编辑:
您还应该在追加文件之后关闭该文件。我建议使用该文件,如:
with open('path/to/file', 'a') as file:
outputFile = csv.writer(file)
# Do your work with the file这样你就不用担心忘记关闭它了。一旦代码存在with块,文件将被关闭。
发布于 2018-08-03 23:36:44
我会用Pandas做这个:
import pandas as pd
headers = ['header1', 'header2', ...]
scraped_df = pd.DataFrame(data, columns=headers)
scraped_df.to_csv('filepath.csv')这里我假设您的data对象是一个列表列表。
https://stackoverflow.com/questions/51681164
复制相似问题