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

时间:2017-06-09 16:17:48

标签: python csv readfile ioexception python-unicode

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的新手 提前谢谢

2 个答案:

答案 0 :(得分:1)

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

如果您想要处理该文件,请在没有with子句的情况下打开它(即明显打开文件)对该文件执行操作该子句,直接将其称为f

答案 1 :(得分:1)

您需要在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