用Python写入CSV文件

2024-10-17 00:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python完全陌生,但对其他语言非常精通,所以我至少对所发生的事情有一些了解。我没有写这段代码,但我正在努力使它为我的目的而工作。在

我用一个API来检索上赛季NFL每场比赛的统计数据。我试图将这些信息写入一个CSV文件,到目前为止,它只是将头文件写入文件,而不是实际的数据。在

有人能告诉我我做错了什么吗?在

import csv 
import nflgame 

games = nflgame.games_gen(2013, kind='REG') 
plays = nflgame.combine_plays(games) 
headers = [] 
for statId, info in nflgame.statmap.idmap.iteritems(): 
    headers += info['fields'] 
    headers.sort() 
    headers = ['gsis_id', 'drive_id', 'play_id', 'desc'] + headers 
    writer = csv.DictWriter(open('2013_regular_plays.csv', 'w+'), fieldnames=headers) 
    writer.writerow({k: k for k in headers}) 
    for p in plays: 
        row = {k: getattr(p, k, 0) for k in headers} 
        row['gsis_id'] = p.drive.game.eid 
        row['drive_id'] = p.drive_num 
        row['play_id'] = p.playid 
        row['desc'] = p.desc 
        writer.writerow(row)

Tags: 文件csvinimportinfoidfordrive
1条回答
网友
1楼 · 发布于 2024-10-17 00:24:57

这看起来应该是最有效的。在

唯一错误的细节compared to the documentation是文件应该以二进制模式打开(w+b)。在

另外,在查看文件之前,请先关闭该文件,这一点很重要:

with open('2013_regular_plays.csv', 'w+b') as csv_file:
    writer = csv.DictWriter(csv_file, fieldnames=headers)
    …

将自动关闭with块之后的文件(如果文件未在该块中读取,则文件模式可以更简单地为wb)。如果在关闭文件之前查看它,它的内容可能仍然驻留在RAM中,而不是在磁盘上。在

PS:正如DSM所指出的,当您以w+(或w+b)模式打开CSV文件时,for statId, info in…都会清空该文件。如果最后一次迭代没有播放,则文件最终为空(只有头)。{em3>通常在循环之前打开文件。在

相关问题 更多 >