关于python:为什么在输出到CSV时,为什么要一遍又一遍地写在同一行上?

Why is this writing to the same line over and over when output to a CSV?

我制作了一个网络抓取应用程序,希望将数据放入一个csv文件中。 抓取部分工作正常并打印到命令行,但是当我尝试写入csv时,它会一遍又一遍地重写循环数据(有100个)的迭代。 我不知道为什么。 有什么想法为什么不每次都将结果写到新行中? (我尝试使用csv.writer和csv.DictWriter方法。结果相同。)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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文件,返回到循环顶部,然后再次打开该文件。 这将返回文件的开头。 如果必须在每次循环中都打开它,请使用'a',附加模式。

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