从csv文件获取数据:关闭fi时出现错误IO操作

2024-06-01 21:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从csv文件中获取一些数据,但遇到了一些错误

错误:##

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)

Tags: csvtextinpyselflinecolumnusers
1条回答
网友
1楼 · 发布于 2024-06-01 21:24:15

您正试图在打开的上下文之外关闭文件后访问reader。将recommend函数中的for循环移到with的上下文中,如下所示:

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'])

Python中的with语句创建了一个上下文,在本例中,为file对象创建了一个上下文。一旦您离开with上下文,Python就会关闭文件并进行一些清理。因此,与file对象相关的所有操作都必须在打开文件的上下文中执行。在

相关问题 更多 >