简体   繁体   English

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)

on executing this piece of code I get following errors 在执行这段代码时,我得到以下错误

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

I dont know how to solve it ,I m new to python thanks in advance 我不知道如何解决它,我是python的新手

When using with open() as f: in python the file f is only open inside the with clause. 当使用with open() as f:在python中时,文件f with子句中打开。 That is the point of using it; 这就是使用它的重点; it provides automatic file closing and cleaning in a easy and readable way. 它以简单易懂的方式提供自动文件关闭和清理功能。

If you want to work on the file either open it without the with clause (that is plain opening a file) or do the operations on that file inside the clause, calling it directly as f . 如果你想在文件上工作,要么打开它,而不with条款(即普通打开文件), 或者做的子句该文件的操作,直接调用它f

You need to move your return under your with statement. 您需要在with语句下移动退货。 Once control flow has gone out of the with statement, Python automatically closes the file for you. 一旦控制流程脱离with语句,Python会自动为您关闭文件。 That means any file I/O you have to do needs to be done under the context manager: 这意味着您需要在上下文管理器中完成任何必须执行的文件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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM