Python .close()似乎不起作用

Python .close()似乎不起作用,python,csv,Python,Csv,我专门在CSV上调用f.close(),但当我运行代码时,它会返回错误: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Student Data.csv' 我完全不知道为什么文件没有关闭,任何帮助都将不胜感激,非常感谢 代码: 从代码其余部分的上下文来看,我猜您想要做的是在完成数据修剪后只重新编写CSV文件一次(行我想

我专门在CSV上调用f.close(),但当我运行代码时,它会返回错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'Student Data.csv'
我完全不知道为什么文件没有关闭,任何帮助都将不胜感激,非常感谢

代码:


从代码其余部分的上下文来看,我猜您想要做的是在完成数据修剪后只重新编写CSV文件一次(
我想):


如果我误解了您代码的意图,请提前道歉。

您正在调用
os.remove('Student Data.csv')
for循环中的
。它只会在第一次工作…你能告诉我们你在哪一行得到错误吗?我不知道为什么人们在这里对这类事情保密。我犯了一个愚蠢的错误,对不起,这是事实,我在循环中称它为@martineau有时它只需要另一双眼睛…;-)使用枚举非范围
from tkinter import *
import csv
import os

def deleteuser():
    def deleteanaccount(searchusername):
        f = open('Student Data.csv', 'r')
        r = csv.reader(f)
        lines = [l for l in r]
        f.close()
        usernamelist = []
        for item in lines:
            usernamelist.append(item[0])        
        x = usernamelist
        for i in range(0, len(usernamelist)):
            if searchusername == usernamelist[i]:
                print(i)
                del(lines[i])
            os.remove('Student Data.csv')
            writer = csv.writer(open('Student Data.csv', 'w', newline=''))
            writer.writerows(lines)


    def clickdelete():
        y = whichaccount.get()
        deleteanaccount(y)


    deleteuserwindow = Tk()
    deleteuserwindow.iconbitmap("hXYTZdJy.ico")
    deleteuserwindow.title("Remove a User")
    whichaccount = Entry(deleteuserwindow)
    whichaccount.grid(row = 0, column = 0, padx = 10, pady = 20)
    Button(deleteuserwindow, text = "Submit", command = clickdelete, height = 4, width = 10).grid(row = 0, column = 1)
    deleteuserwindow.mainloop()

deleteuser()
    for i in range(0, len(usernamelist)):
        if searchusername == usernamelist[i]:
            print(i)
            del(lines[i])

    # Don't do this stuff until the loop is done
    os.remove('Student Data.csv')
    writer = csv.writer(open('Student Data.csv', 'w', newline=''))
    writer.writerows(lines)