2
votes

I'm trying to fetch some data from csv file but getting some error

error: ##

Exception in Tkinter callback

Traceback (most recent call last):

File "C:\Users\hp-\AppData\Local\Programs\Python\Python35-32\lib\tkinter__init__.py", line 1549, in call return self.func(*args)

File "C:\Users\hp-\Downloads\pyguii.py", line 120, in combine_funcs recommend()

File "C:\Users\hp-\Downloads\pyguii.py", line 114, in recommend for row in reader:

File "C:\Users\hp-\AppData\Local\Programs\Python\Python35-32\lib\csv.py", line 109, in next self.fieldnames

File "C:\Users\hp-\AppData\Local\Programs\Python\Python35-32\lib\csv.py", line 96, in fieldnames

self._fieldnames = next(self.reader) ValueError: I/O operation on closed file.
def getrate():
    stem=tk.Toplevel(root)
    a1=Label(stem,text='Which type of songs will you like to listen')
    a1.grid(row=0,column=0)  
    var2 = IntVar()
    dd1 = Radiobutton(stem, text="Hindi songs", variable=var2, value=1)
    dd1.grid(row=1,column=1)
    label = Label(stem)  
    dd2 = Radiobutton(stem, text="Punjabi songs", variable=var2, value=2)
    dd2.grid(row=2,column=2)
    label = Label(stem)  


def getcat1():
    gg2=var2.get()
    fields.append(gg2)
    with open(r'category.csv', 'a') as f:
            writer = csv.writer(f)
            writer.writerow(fields)
    print(gg2)

def recommend():
    with open('listsng.csv') as csvfile:
         reader = csv.DictReader(csvfile)
         #print (reader)
    for row in reader:
         if '2015' in row['Year'] and 'Hindi' in row['Category']:
             print(row['Song Name'])

def combine_funcs():
    getcat1()
    recommend()
ee=Button(stem,text='Submit',command=combine_funcs)
ee.grid(row=10,column=2)
ee1=Button(stem,text='Skip',command='')
ee1.grid(row=10,column=4)
1

1 Answers

1
votes

You are trying to access the reader after the file has been closed outside the context it was opened. Move the for loop in the recommend function into the context of with, like so:

def recommend():
    with open('listsng.csv') as csvfile:
         reader = csv.DictReader(csvfile)
         #print (reader)
         for row in reader:
             if '2015' in row['Year'] and 'Hindi' in row['Category']:
                 print(row['Song Name'])

The with statement in Python creates a context, and in this case a context was created for the file object. Once you leave the with context, Python closes the file and does some cleanup. Therefore, all operations that relate to the file object must be executed in the context in which the file was opened.