PyDrive 上传和删除

2024-02-25

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

#%%
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 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'

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

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

您可以尝试一下吗?看看是否有帮助?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PyDrive 上传和删除 的相关文章

随机推荐