写入csv时出错,不允许我写入Python3和csvwriter?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (46)

这个代码有问题:

    i = range(0, 51)

    page_number = 1
    with open('hltb data/HLTB.csv','w') as f: 
        thewriter = csv.writer(f)
        thewriter.writerow(['Game Name:', 'Game Length:', 'Game Developer:', "Game Publisher:", 'Game Genre:', 'Game Console:', 'URL:']) 
 for element in i:
        url = 'https://howlongtobeat.com/game.php?id=' + format(page_number)

        response = get(url)
        html_soup = BeautifulSoup(response.text, 'html.parser')

        page_number += 1

        try:
            game_name = html_soup.select('div.profile_header')[0].text
        except:
            game_name = "Game Name not found"

        try:     
            game_length = html_soup.select('div.game_times li div')[-1].string
        except:
            game_length = "Game length not found"

        try:
            game_developer = html_soup.find_all('strong', string='\nDeveloper:\n')[0].next_sibling
        except:
            game_developer = "Game developer not found"

        try:
            game_publisher = html_soup.find_all('strong', string='\nPublisher:\n')[0].next_sibling
        except:
            game_publisher = "Game Publisher not found"

        try:
            game_console = html_soup.find_all('strong', string='\nPlayable On:\n')[0].next_sibling
        except:
            game_console = "Game Playable on not found"

        try:
            game_genres = html_soup.find_all('strong', string='\nGenres:\n')[0].next_sibling
        except:
            game_genres = "Game Genres found"

        print(url)
        print(game_name)
        print(game_length)
        print(game_developer)
        print(game_publisher)
        print(game_genres)
        print(game_console)

        row = [game_name, game_length, game_developer, game_publisher, game_genres, game_console, url]
        thewriter.writerow(row)

我在运行代码时遇到此错误:

ValueError Traceback (most recent call last) in () 46 47 row = [game_name, game_length, game_developer, game_publisher, game_genres, game_console, url] ---> 48 thewriter.writerow(row)

ValueError: I/O operation on closed file.

如何进行数据挖掘并将信息传输到电子表格中,以便我可以处理数据?

提问于
用户回答回答于
[...]
with open('hltb data/HLTB.csv','w') as f: 
    thewriter = csv.writer(f)
    thewriter.writerow(['Game Name:', 'Game Length:', 'Game Developer:', "Game Publisher:", 'Game Genre:', 'Game Console:', 'URL:']) 
    for element in i:
        url = 'https://howlongtobeat.com/game.php?id=' + format(page_number)
        [...]

扫码关注云+社区

领取腾讯云代金券