Reading .csv through DictReader

偶尔善良 提交于 2021-01-27 21:19:55

问题


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

Code :

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

I keep receiving this error:

    ['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.


回答1:


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

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



来源:https://stackoverflow.com/questions/32572541/reading-csv-through-dictreader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!