python - PyDrive 上传和删除

标签 python google-drive-api pydrive

我是 Google Drive API 的新手并编写了一个最简单的脚本形式,该脚本自动将图像从本地驱动器上传到谷歌驱动器,然后一旦上传该图像,删除本地副本,以下是我得到的:

#%%
import os
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from googleapiclient.http import MediaFileUpload
g_login = GoogleAuth()
g_login.LocalWebserverAuth()
drive = GoogleDrive(g_login)

#%%
header = 'images/dice'
path = header + str(i) + '.png'
file = drive.CreateFile()
file.SetContentFile(path)
file.Upload()
if file.uploaded:
    print("test")
    os.remove(path)

但是在尝试删除本地副本时,会出现以下错误:

PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:'images/dice1.png'

我搜索了一下,认为可能是 SetContentFile(path) 在 Upload() 之后没有关闭文件,根据

https://gsuitedevs.github.io/PyDrive/docs/build/html/pydrive.html

它应该在上传后自动关闭。

我在这里监督什么?

注意:最后,我想使用一个循环遍历目录中的所有文件。

这是输出:
1
test
---------------------------------------------------------------------------

PermissionError                           Traceback (most recent call last)

<ipython-input-21-2aeb578b5851> in <module>
      9 if file.uploaded:
     10     print("test")
---> 11     os.remove(path)
     12 

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'images/dice1.png'

enter image description here

最佳答案

即使 PyDrive 没有为您关闭它,从查看代码来看,您似乎可以执行以下操作:

...
try:
    file.Upload()
finally:
    file.content.close()
if file.uploaded:
...

你能试一试,看看是否有帮助?

关于python - PyDrive 上传和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60132814/

相关文章:

python - Pydrive:防止 Google Drive 授权过期。

python - PyCharm 识别模块但不导入它

python - 在python中读取具有可变列数的文件

python - Pandas - 执行多列转置

python - 如何将列表与嵌套列表连接起来?

python - celery worker 在调用 retry() 后不重试任务

javascript - 将工作表复制到另一个电子表格 [Google Apps 脚本]

html - Google Drive 502 网关错误

google-drive-api - 在不覆盖 google-drive sdk 的情况下向文件添加行

google-drive-api - 如何使用 PyDrive 访问团队驱动器而不是个人 Google 驱动器?