简体   繁体   English

用Python写入CSV文件

[英]Writing to a CSV file in Python

I'm totally new to Python, but am pretty well-versed in other languages so I have at least some idea of what's going on. 我对Python完全陌生,但是对其他语言非常精通,所以我至少对正在发生的事情有一些了解。 I did not write this code, but I am trying to make it work for my purposes. 我没有编写此代码,但是我正在尝试使其达到我的目的。

I'm using an API to retrieve statistics about every play in the NFL from last season. 我正在使用API检索有关上赛季NFL中每场比赛的统计信息。 I am trying to write this information to a CSV file, and so far, it's writing the headers to the file and not the actual data. 我正在尝试将此信息写入CSV文件,到目前为止,它是将标头写入文件,而不是实际数据。

Can someone tell me what I'm doing wrong? 有人可以告诉我我在做什么错吗?

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)

This looks like it should mostly work. 看起来应该可以正常工作了。

The only detail which is wrong compared to the documentation is that the file should be open in binary mode ( w+b ). 与文档相比,唯一错误的细节是该文件应以二进制模式( w+b )打开。

Also, it is important that the file be closed before you can have a look at it: 同样,在您查看文件之前,关闭文件很重要:

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

will automatically close the file after the with block (and the file mode could be more simply wb , if the file is not read inside this block). 将在with块之后自动关闭文件(如果未在此块内读取文件,则文件模式可以更简单地为wb )。 If you look at the file before it is closed, its contents might still reside in RAM instead of on the disk. 如果在关闭文件之前先查看文件,其内容可能仍驻留在RAM中而不是磁盘上。

PS : As DSM pointed out, each iteration for statId, info in… empties the CSV file when you open it with the w+ (or w+b ) mode. PS :正如DSM所指出的那样,当您使用w+ (或w+b )模式打开for statId, info in…每次迭代时for statId, info in… 清空CSV文件 If the last iteration has no plays, then the file end up being empty (with headers only). 如果最后一次迭代没有播放,则文件最终将为空(仅包含标头)。 You typically want to open the CSV file before the loop (maybe even simply with the wb mode). 您通常希望在循环之前打开CSV文件(甚至可能只是使用wb模式)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM