Search code examples
pythonpython-3.xcsvdictionarystack-overflow

How can I use csv_reader object outside like a list?


I want use like list or dict but i am finding this error when i tried it. How can I use csv_reader object outside like a list?

import csv


def get_data(file):
    with open(file,'r',encoding="ISO-8859-1") as csv_file:
        csv_reader = csv.DictReader(csv_file,delimiter=',')
        return csv_reader
for i in get_data('spam.csv'):
    print(i)


Traceback (most recent call last):
  File "test1.py", line 10, in <module>
    for i in get_data('spam.csv'):
  File "/home/indianic/anaconda3/lib/python3.7/csv.py", line 111, in __next__
    self.fieldnames
  File "/home/indianic/anaconda3/lib/python3.7/csv.py", line 98, in fieldnames
    self._fieldnames = next(self.reader)
ValueError: I/O operation on closed file.

Solution

  • Since you are using with open() to open the file, as soon as the function block runs the file gets closed and you don't have access to it.

    In order to keep the context of file you can use 2 of the following ways.

    1. You can use it by yeild a generator object instead of returning.
    import csv
    
    
    def get_data(file):
        with open(file,'r',encoding="ISO-8859-1") as csv_file:
            csv_reader = csv.DictReader(csv_file,delimiter=',')
    
            for row in csv_reader:
                yield row
    
    for i in get_data('spam.csv'):
        print(i)
    
    1. Open the file outside of the function
    import csv
    
    def main():
        csv_file = open(file,'r',encoding="ISO-8859-1")
        for i in get_data(csv_file):
            print(i)
        csv_file.close()
    
    def get_data(file):
        csv_reader = csv.DictReader(file,delimiter=',')
        return csv_reader
    
    main()