【问题标题】:Why is this writing to the same line over and over when output to a CSV?为什么在输出到 CSV 时一遍又一遍地写入同一行?
【发布时间】:2018-09-19 08:08:53
【问题描述】:

我制作了一个网络抓取应用程序,我想将数据放入 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})

【问题讨论】:

  • 您在 for 循环内以写入模式 ('w') 打开文件 - 这会在每次迭代时擦除文件的任何现有内容。以附加模式打开。或者打开文件一次并将for 循环放在上下文管理器中(快得多)。

标签: python csv web-scraping export-to-csv


【解决方案1】:

每次循环迭代,关闭 CSV 文件,返回到循环顶部,然后再次打开文件。这将返回到文件的开头。使用'a',如果每次循环都必须打开,则追加模式。

或者,在进入循环之前打开文件;将您的 for 放在 with 块内。

【讨论】:

  • 很多事情都是显而易见的有人指出这17个因素中的哪一个是问题所在。这就是 Stack Overflow 存在的原因。
猜你喜欢
  • 2019-04-16
  • 2015-07-15
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 2019-09-21
相关资源
最近更新 更多