.close()似乎不起作用python CSV

时间:2014-12-17 21:39:41

标签: 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'

我完全不知道为什么文件没有关闭,任何帮助都会非常感激,非常感谢

代码:

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()

1 个答案:

答案 0 :(得分:1)

从其余代码的上下文中,我猜测您要做的只是在您修剪数据后重新编写CSV文件一次(lines我假设):

    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)

如果我误解了你的代码的意图,请提前预防。