4

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'

enter image description here

Gary
  • 53
  • 5
  • Does it print 'test'? – mhdev Feb 09 '20 at 02:54
  • Yes it does print test – Gary Feb 09 '20 at 20:09
  • Can you print your working directory ? What is that ? Is that your local drive ? I suspect that's the issue. – mozilla-firefox Feb 09 '20 at 20:20
  • Could the file have been open twice? The docs say SetContentFile open the file. – Mic Feb 09 '20 at 21:15
  • I am working using pycharm project, and yes when printing os.cwd() is under the local drive, PycharmProjects\example. I don't think the file is opened twice, as it says : "Opens the file specified by this method. Will be read, uploaded, and closed by Upload() method. Sets metadata ‘title’ and ‘mimeType’ automatically if not specified.". I have included a photo of the project tree. Or is there a another way in performing what I wanted to do? – Gary Feb 10 '20 at 22:19

1 Answers1

3

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?

Shcheklein
  • 5,979
  • 7
  • 44
  • 53