PyDrive icon indicating copy to clipboard operation
PyDrive copied to clipboard

File not closing after Upload()

Open robrothschild opened this issue 6 years ago • 6 comments

I'm trying to delete a .zip file from my local system after uploading it to drive. The issue is that one the file is uploaded I get the following error:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'test.zip'

To delete the file I use os.remove but even when I try to remove it from the file manager it wont let me.

robrothschild avatar May 01 '18 16:05 robrothschild

Can you post the code you use to upload?

keliomer avatar May 09 '18 17:05 keliomer

Sure thing, this is in a for loop that uploads a .png file, then deletes it. It fails on the first run through.

upfile = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": out_folder}]})
upfile.SetContentFile(plot)
upfile.Upload()
os.remove(plot)

It gets that WinError32 on os.remove()

robrothschild avatar May 09 '18 22:05 robrothschild

Can confirm. I can't edit any file after the Upload() method.

Here's my code:

fileHandle.SetContentFile(compressed_file_path)
fileHandle['title'] = new_filename
fileHandle['mimeType'] = 'application/gzip'
fileHandle.Upload()
os.remove(compressed_file_path)

And here's the traceback (with shortened path) PermissionError: [WinError 32] Impossibile accedere al file. Il file è utilizzato da un altro processo: 'C:\\test\test.tar.gz'

Any update on this?

EDIT: I created a pull request (sorry if malformed or anything, I'm not familiar at all) with what I think is a fix to this. https://github.com/gsuitedevs/PyDrive/pull/144

bonny1992 avatar Sep 13 '18 21:09 bonny1992

I found a work around where you can basically just free the variable using something like del fileHandle and then use the os.remove(compressed_file_path) to delete the file.

bjgau avatar Mar 30 '19 05:03 bjgau

I found a solid workaround that uses PyDrive's public API: SetContentFile("nul") "nul" is the Windows equivalent to /dev/null.

I think the ideal fix is to make SetContentFile not open the file as it does here: https://github.com/gsuitedevs/PyDrive/blob/68cea204cdcd10bab9321580164c8f4961385a0f/pydrive/files.py#L175 But instead open the file immediately before and after the upload.

csimmons0 avatar Jun 16 '19 21:06 csimmons0

Sure thing, this is in a for loop that uploads a .png file, then deletes it. It fails on the first run through.

upfile = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": out_folder}]}) upfile.SetContentFile(plot) upfile.Upload() os.remove(plot)

It gets that WinError32 on os.remove()

@robrothschild You need to manually close the file handle

upfile = drive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": out_folder}]}) upfile.SetContentFile(plot) upfile.Upload() upfile.content.close() os.remove(plot)

zjcnew avatar Apr 26 '21 02:04 zjcnew