Skip to main content
 首页 » 编程设计

python之从 csv 文件 : Error IO operation on closed file 中获取数据

2025年04月02日13softidea

我正在尝试从 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) 

请您参考如下方法:

文件在打开的上下文之外关闭后,您正试图访问 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 语句创建了一个上下文,在本例中为文件对象创建了一个上下文。一旦您离开 with 上下文,Python 就会关闭文件并进行一些清理。因此,所有与文件对象相关的操作都必须在打开文件的上下文中执行。