2016-09-28 60 views
1

我一直在學習和練習python,在此期間我在程序中發現了一個錯誤,但我無法解決。我想要返回從csv文件中檢索的列表。我試過下面的代碼,它返回一個錯誤。無法返回從文件中讀取的列表(.csv)

import csv 

def returnTheRowsInTheFile(fileName): 
    READ = 'r' 
    listOfRows = [] 
    try: 
     with open(fileName, READ) as myFile: 
      listOfRows = csv.reader(myFile) 
      return listOfRows 
    except FileNotFoundError: 
     print('The file ' + fileName + ' is not found') 
    except: 
     print('Something went wrong') 
    finally: 
     #myFile.close() 
     print() 

def main(): 
    fullString = returnTheRowsInTheFile('ABBREVATIONS.CSV') 
    for eachRow in fullString: 
     print(eachRow) 
    return 

main() 

和錯誤是

Traceback (most recent call last): File "C:\Users\santo\workspace\PyProject\hello\FinalChallenge.py", line 36, in main() File "C:\Users\santo\workspace\PyProject\hello\FinalChallenge.py", line 32, in main for eachRow in fullString: ValueError: I/O operation on closed file.

回答

0

當你使用它with open關閉該文件時上下文結束。現在listOfRows的返回類型爲csv.Reader,因此fullString(不是列表)。您正在嘗試對它進行迭代,這似乎是遍歷已關閉的文件對象。

0

由於JulienD已經指出,當您嘗試從中讀取行時,該文件已被關閉。您可以使用此例如擺脫這種異常:

with open(fileName, READ) as myFile: 
     listOfRows = csv.reader(myFile) 
     for row in listOfRows: 
      yield row 

UPDATE

順便說一句,你處理異常的方式使得它非常難以調試。我會建議這樣的事情。

except Exception as e: 
    print('Something went wrong: "%s"' e) 

這樣你至少可以看到錯誤信息。

1

解決此問題的簡單方法是從您的函數返回一個列表。我知道你分配了listOfRows = [],但是當你做了listOfRows = csv.reader(myFile)時,這個被覆蓋。

所以,最簡單的辦法是:

def returnTheRowsInTheFile(fileName): 
    READ = 'r' 
    try: 
     with open(fileName, READ) as myFile: 
      listOfRows = csv.reader(myFile) 
     return list(listOfRows) # convert to a list 
    except FileNotFoundError: 
     print('The file ' + fileName + ' is not found') 
    except: 
     print('Something went wrong') 

你也應該閱讀pep8這是風格指南爲Python;以瞭解如何命名變量和函數。