通过DictReader读取.csv [英] Reading .csv through DictReader

查看:40
本文介绍了通过DictReader读取.csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是尝试使用第一行作为字典的键来读取.csv,但没有成功.我的文件有两行(测试),项目由制表符分隔.

I'm just trying to read a .csv using the first row as keys for the dictionary, with no success. My file has two lines (test), items being delimited by tabs.

subjectID   logID   logTimestamp    gameKey userID  writer  gameTime    gameCode    gameDesc
9991    1711774 6/13/14 E9E91B56    L11-13  general 358 1002    GAMESCRIBE_CREATED

代码:

def process_data(file_path):
    users = {}

    # Open the .csv file and creates a dict of actions
    with open(file_path, 'rb') as csvfile:
        spamreader = csv.DictReader(csvfile, delimiter='\t')
        print spam reader
        print spamreader.fieldnames 
        for row in spamreader:
            print row

我一直收到此错误:

    ['subjectID', 'logID', 'logTimestamp', 'gameKey', 'userID', 'writer', 'gameTime', 'gameCode', 'gameDesc']
Traceback (most recent call last):
  File "logEvents.py", line 41, in <module>
    process_data(logs_path)
  File "logEvents.py", line 11, in process_data
    for row in spamreader:
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.py", line 108, in next
    row = self.reader.next()
ValueError: I/O operation on closed file

我不知道我在做什么错.

I don't know what I'm doing wrong.

推荐答案

您的实际代码中 with 块之外的垃圾邮件阅读器行中的 :

You have for row in spamreader outside the with block in your actual code:

with open(file_path, 'rb') as csvfile:
    spamreader = csv.DictReader(csvfile, delimiter='\t')
    print spamreader
for row in spamreader: # your code
     print row

一旦离开 with 块,文件将关闭,因此尝试从文件对象读取失败.

Once you leave the with block the file is closed so trying to read from the file object fails.

这篇关于通过DictReader读取.csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆