【问题标题】:Reading .csv through DictReader通过 DictReader 读取 .csv
【发布时间】:2015-12-10 21:52:47
【问题描述】:

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

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

我不知道我做错了什么。

【问题讨论】:

    标签: python csv dictionary


    【解决方案1】:

    您在实际代码中的 with 块之外有 for row in spamreader

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

    一旦您离开 with 块,文件就会关闭,因此尝试从文件对象读取失败。

    【讨论】:

    • OP 的代码混合了空格和制表符进行缩进,这更有可能是问题的根源——它看起来对 OP 正确缩进,即使它不是。
    猜你喜欢
    • 1970-01-01
    • 2018-04-17
    • 2019-09-14
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2011-12-04
    相关资源
    最近更新 更多