如何关闭文件以便可以使用os.remove删除?获取WinError32

问题描述

首先,这是我的程序代码

import os,shutil
import keyboard
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

print("Zipping MedianXL SP save files to an archive...")

shutil.make_archive("backup_saves","zip",r"c:/users/x/appdata/roaming/medianxl/save")

print("Done! Now doing some housekeeping and uploading the archive to Google Drive...")

source_path = r"c:/users/x/onedrive/documents/programming/python/medianxlbackup/backup_saves.zip"
destination_path = r"c:/users/x/desktop"

shutil.move(source_path,destination_path)

auth = GoogleAuth()
auth.LocalWebserverAuth()
drive = GoogleDrive(auth)

saves = drive.CreateFile()
saves.SetContentFile(r"c:/users/x/desktop/backup_saves.zip")
saves.Upload()

这确实是新手,也很简单,尽管它确实可以实现我想要的功能。它会保存我玩过的游戏的保存文件,将其压缩,然后将其从压缩后的程序目录移至桌面,然后将存档上传到Google云端硬盘,以便我可以下载该文件以继续玩游戏从另一台计算机。

我正尝试添加一个额外的小选项,继续操作,并提供在归档文件上传后将其从桌面删除的选项。我在这里遇到了几个问题,被卡住了。

我尝试的第一件事是:

while True:
     if keyboard.is_pressed("enter"):
         os.remove(r"c:/users/x/desktop/backup_saves.zip")
         print("All files cleaned up,happy farming!")
         break
else:
     if keyboard.is_pressed("esc"):
         exit()

此问题是,按Enter键删除存档后,出现以下错误消息:

[WinError 32]该进程无法访问文件,因为它正在 被另一个进程使用

我做了一些阅读,似乎文件需要先删除才能被删除,但是我被卡住了,不确定如何将其集成到我的代码中。我尝试定义一个变量:close_zip = r"c:/users/patjb/desktop/backup_saves.zip",但它告诉我:

'str'对象没有属性'close'

有什么建议吗?

解决方法

据我所知,为关闭任何文件,使用了“ close()”方法。因此,要关闭zip文件,您必须在我的close方法后面输入您在其中调用过的变量。

例如Variable_ contains_file.close()