为什么在输出到 CSV 时一遍又一遍地写入同一行?
Why is this writing to the same line over and over when output to a CSV?
我制作了一个网络抓取应用程序,我想将数据放入 csv 文件中。刮刀部分工作正常并打印到命令行,但是当我尝试写入 csv 时,它一遍又一遍地重写第一行循环数据的迭代(有 100 个)。我不确定为什么。任何想法为什么它不是每次都将结果写入新行? (我试过 csv.writer 和 csv.DictWriter 方法。结果相同。)
def create_csv_file():
file_name = str(datetime.date.today())
field_names = ['Rank', 'Title', 'Author', 'Star Rating', 'Price']
with open('{}.csv'.format(file_name), 'w', newline='') as csvfile:
the_writer = csv.DictWriter(csvfile, fieldnames=field_names)
the_writer.writeheader()
return file_name, field_names
def get_book_details(soup, file, headers):
items = soup.find_all('div', class_='zg_itemImmersion')
for i in items:
#Web Scrape code here. Cut to truncate.
with open('{}.csv'.format(file), 'w', newline='', encoding='utf-8') as csvfile:
the_writer = csv.DictWriter(csvfile, fieldnames=headers)
the_writer.writerow({'Rank': rank, 'Title': title, 'Author': author, 'Star Rating': star_rating, 'Price': price})
每次循环迭代,关闭 CSV 文件,return 到循环顶部,然后再次打开文件。这 returns 到文件的开头。使用'a'
,如果每次循环都必须打开它,则使用追加模式。
或者,在进入循环之前打开文件;将您的 for
放在 with
块中。
我制作了一个网络抓取应用程序,我想将数据放入 csv 文件中。刮刀部分工作正常并打印到命令行,但是当我尝试写入 csv 时,它一遍又一遍地重写第一行循环数据的迭代(有 100 个)。我不确定为什么。任何想法为什么它不是每次都将结果写入新行? (我试过 csv.writer 和 csv.DictWriter 方法。结果相同。)
def create_csv_file():
file_name = str(datetime.date.today())
field_names = ['Rank', 'Title', 'Author', 'Star Rating', 'Price']
with open('{}.csv'.format(file_name), 'w', newline='') as csvfile:
the_writer = csv.DictWriter(csvfile, fieldnames=field_names)
the_writer.writeheader()
return file_name, field_names
def get_book_details(soup, file, headers):
items = soup.find_all('div', class_='zg_itemImmersion')
for i in items:
#Web Scrape code here. Cut to truncate.
with open('{}.csv'.format(file), 'w', newline='', encoding='utf-8') as csvfile:
the_writer = csv.DictWriter(csvfile, fieldnames=headers)
the_writer.writerow({'Rank': rank, 'Title': title, 'Author': author, 'Star Rating': star_rating, 'Price': price})
每次循环迭代,关闭 CSV 文件,return 到循环顶部,然后再次打开文件。这 returns 到文件的开头。使用'a'
,如果每次循环都必须打开它,则使用追加模式。
或者,在进入循环之前打开文件;将您的 for
放在 with
块中。