Reputation: 53
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] The process cannot access the file because it is being used by another process: 'images/dice1.png'
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.
What am I overseeing here?
Note: In the end, I want to use a loop that go through all the files within the directory.
This is the output:
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'
Upvotes: 4
Views: 1453
Reputation: 6284
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?
Upvotes: 3