File not closing after Upload()
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.
Can you post the code you use to upload?
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()
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
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.
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.
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)