CSV 文件在 python 2.7 中使用 open() 读取时出错

CSV file gives error on reading with open() in python 2.7

import unicodecsv
engagement_file=r'G:\college\udacity\intro to data analitics\datasets\daily_engagement.csv'
enrollment_file=r'G:\college\udacity\intro to data analitics\datasets\enrollments.csv'
project_submissions_file=r'G:\college\udacity\intro to data analitics\datasets\project_submissions.csv'
def csv_to_list(csv_file):
    with open(csv_file,'rb') as f:
        reader=unicodecsv.DictReader(f)
    return list(reader)

daily_engagement=csv_to_list(engagement_file)
enrollment=csv_to_list(enrollment_file)
project_submissions=csv_to_list(project_submissions_file)

执行这段代码时出现以下错误

Traceback (most recent call last):
  File "G:\college\udacity\intro to data analitics\data_analytis_csv_to_list.py", line 10, in <module>
    daily_engagement=csv_to_list(engagement_file)
  File "G:\college\udacity\intro to data analitics\data_analytis_csv_to_list.py", line 8, in csv_to_list
    return list(reader)
  File "C:\ProgramData\Anaconda2\lib\site-packages\unicodecsv\py2.py", line 217, in next
    row = csv.DictReader.next(self)
  File "C:\ProgramData\Anaconda2\lib\csv.py", line 108, in next
    row = self.reader.next()
  File "C:\ProgramData\Anaconda2\lib\site-packages\unicodecsv\py2.py", line 117, in next
    row = self.reader.next()
ValueError: I/O operation on closed file

我不知道怎么解决,我是新手 python 提前致谢

当在 python 中使用 with open() as f: 时,文件 f 仅在 inside with 子句中打开。这就是使用它的意义所在;它以简单易读的方式提供自动文件关闭和清理功能。

如果您想处理该文件,请在不使用 with 子句的情况下打开它(即普通打开文件) 对该文件进行操作 子句中,直接调用为f.

您需要将 return 移到 with 语句下。一旦控制流离开 with 语句,Python 会自动为您关闭文件。这意味着您必须做的任何文件 I/O 都需要在上下文管理器下完成:

def csv_to_list(csv_file):
    with open(csv_file,'rb') as f:
        reader = unicodecsv.DictReader(f)
        return list(reader) # return the file under the context manager