首页 > 解决方案 > CSV writer - 在脚本运行时写入 csv 但不保存

问题描述

我的代码似乎正在工作并将数据保存到 csv 但脚本结束后,没有数据。当脚本运行时,我的 csv 文件存储数据,如果我中断它,我可以看到一些数据。

import requests
from bs4 import BeautifulSoup
import csv


def main():

    page = 1
    page_has_data = True 
    while page_has_data:

        r = requests.get("http://scrapethissite.com/pages/forms/", params=dict(per_page=100, page_num=page))
        soup = BeautifulSoup(r.text, features="lxml")

        print("----- Scraping page number", page)
        page += 1

        teams = soup.findAll("tr", "team")
        if len(teams) == 0:
            page_has_data = False

        with open("hockey_stats.csv", "w", newline="") as results:
            writer = csv.writer(results)

            for team in teams:
                team_name = team.find("td", "name").get_text(strip=True)
                team_year = team.find("td", "year").get_text(strip=True)
                team_win = team.find("td", "wins").get_text(strip=True)
                team_loss = team.find("td", "losses").get_text(strip=True)
                team_pct_win = team.find("td", "pct text-success")
                team_goalsfor = team.find("td", "gf").get_text(strip=True)
                team_goalsagainst = team.find("td", "ga").get_text(strip=True)
                team_plus_minus = team.find("td", "diff text-success")
                writer.writerow([team_name, team_year,team_win, team_loss, team_pct_win, team_goalsfor, team_goalsagainst, team_plus_minus])

            results.close()

标签: pythoncsv

解决方案


我认为您的代码段有两个问题。您正在以写入模式打开文件。而是打开它附加模式(“a”)。当您使用新请求进行迭代时,您最终会覆盖您上次写入文件的数据(如果文件以写入模式打开 - “w”)。最后一个请求将没有任何数据,并且您用空数据覆盖您的文件。

其次,你不需要'results.close()'。with 语句将负责关闭文件。


推荐阅读