Search code examples
pythoncsvreadfileioexceptionpython-unicode

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


Solution

  • 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.