PyDrive上传和删除 [英] PyDrive Upload and Remove
问题描述
我是Google Drive API的新手,编写了一种最简单的脚本形式,该脚本会自动将本地驱动器上的图像上传到google驱动器,然后,一旦上传该图像,请删除本地副本,这就是我所得到的:
I am new to Google Drive API and writing a simplest form of a script that automatically upload an image from the local drive on to google drive, then once that image is uploaded, delete the local copy, following is what I have got:
#%%
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)
但是,当尝试删除本地副本时,会发生以下错误:
however when attempting in deleting the local copy, following error occurs:
PermissionError:[WinError 32]该进程无法访问文件,因为该文件正在被另一个进程使用:'images/dice1.png'
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'images/dice1.png'
我进行了搜索,认为可能是SetContentFile(path),在Upload()之后,它没有关闭文件,根据
I searched it up, thinking it might be the SetContentFile(path) where it did no close the file after Upload(), which according to
https://gsuitedevs.github.io/PyDrive/docs /build/html/pydrive.html
它应该在上传后自动关闭.
it should close automatically after upload.
我在这里监督什么?
注意:最后,我想使用遍历目录中所有文件的循环.
Note: In the end, I want to use a loop that go through all the files within the directory.
这是输出:
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没有为您关闭它,通过查看代码,您似乎也可以执行以下操作:
Even if PyDrive does not close it for you, from looking into the code, it looks like you can do something like this:
...
try:
file.Upload()
finally:
file.content.close()
if file.uploaded:
...
请尝试一下,看看是否有帮助?
could you give a try please and see if that helps?
这篇关于PyDrive上传和删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!