删除正在使用 python 的文件时出错

Error when deleting a file in use with python

我正在创建一个脚本,使用 Youtube API,将视频加载到文件夹中,然后将其删除。虽然视频已经加载,但 Python 不允许您删除该文件。它给了我错误:

WindowsError: [Error 32] The process cannot access the file because it is being used by another process.

然后我尝试使用os.close(filevar),但它返回了这个错误:

TypeError: an integer is required (got type str)

我试过这样的方法使变量成为整数,但没有成功:

newest_file = 1 #Set the value of var in int
os.close(newest_file)   #Close process
newest_file = max(mp4_files, key = os.path.getctime) #Rewrite the var   
os.remove(newest_file)  #Remove the last video

我该如何解决这个问题?

我也遇到过这个问题,最近在windows中使用os.remove时出现了这个问题。 我使用 send2trash 库解决了它,而不是删除文件,文件将它发送到垃圾箱。

send2trash.send2trash(newest_file)