簡體   English   中英

通過 DictReader 讀取 .csv

[英]Reading .csv through DictReader

我只是嘗試使用第一行作為字典的鍵讀取 .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

我不知道我做錯了什么。

您在實際代碼中的with塊之外的for row in spamreaderfor 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塊,文件就會關閉,因此嘗試從文件對象讀取失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM