PyDrive 上传和删除
PyDrive Upload and Remove
我是 Google 驱动器 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
它应该会在上传后自动关闭。
我在这里监督什么?
注意:最后,我想使用一个遍历目录中所有文件的循环。
这是输出:
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:
...
你能试试看是否有帮助吗?
我是 Google 驱动器 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
它应该会在上传后自动关闭。
我在这里监督什么?
注意:最后,我想使用一个遍历目录中所有文件的循环。
这是输出:
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:
...
你能试试看是否有帮助吗?