0
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

  • voting to close this as it is a simple typographical error - you've just missed one level of indentation for your `return` – asongtoruin Jun 09 '17 at 16:25
  • @asongtoruin Yes, technically you _could_ say that. But I don't think closing the question as a typo would be valid. It came from a fundamentally misunderstanding of how the context manager works. – Christian Dean Jun 09 '17 at 16:28

2 Answers2

1

When using with open() as f: in python the file f is only open inside the with clause. 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.

DarkCygnus
  • 7,420
  • 4
  • 36
  • 59
1

You need to move your return under your with statement. Once control flow has gone out of the with statement, Python automatically closes the file for you. That means any file I/O you have to do needs to be done under the context manager:

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
Christian Dean
  • 22,138
  • 7
  • 54
  • 87