'在写入大量数据时空的CSV文件'

2024-04-26 17:19:07 发布

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

我目前正在使用python3执行一个数据抓取项目,并试图将刮取的数据写入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文件将为空。如果我只是跑:

^{pr2}$

将生成一个包含以下标题的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]

为什么会这样?在


Tags: 文件csv数据fordatagetheaderscrap
2条回答

使用w打开文件时,它会删除以前的数据

From the docs

w: open for writing, truncating the file first

因此,当您在用w写入scrape数据后打开该文件时,您只会得到一个空白文件,然后在该文件上写入头文件,以便只看到该头文件。尝试将w替换为a。打开文件的新调用看起来像

outputFile = csv.writer(open('myFilepath', 'a'))

您可以详细了解有关打开文件here的模式的详细信息

参考号:How do you append to a file?

在DYZ的评论后编辑:

您还应该在完成附加后关闭文件。我建议使用如下文件:

with open('path/to/file', 'a') as file:
    outputFile = csv.writer(file)
    # Do your work with the file

这样你就不必担心记得关上它了。一旦代码存在with块,文件将被关闭。在

我会用熊猫来做这个:

import pandas as pd
headers = ['header1', 'header2', ...]
scraped_df = pd.DataFrame(data, columns=headers)
scraped_df.to_csv('filepath.csv')

这里我假设您的data对象是一个列表列表。在

相关问题 更多 >