Home > front end >  The process of uploading a file to Google drive prevents the program from deleting the file afterwar
The process of uploading a file to Google drive prevents the program from deleting the file afterwar

Time:12-03

For some reason, the program won't remove the file. I think it's because of the uploading process, but I don't know how to fix it.

Open this link(to get the API Access_Token): https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?redirect_uri=https://developers.google.com/oauthplayground&prompt=consent&response_type=code&client_id=407408718192.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&access_type=offline&flowName=GeneralOAuthFlow

This link works in Brave web browser or else you need to be administrator.

Then paste the Access_Token you find after clicking the blue button where it says: {Access_token}

#alle modules
import os
import json
import requests

#create file
t = open('Test.txt', 'w')
t.write('This is a test file')
t.close()

#upload zip file to Google Drive
headers = {"Authorization": "Bearer {Access_Token}"}
para = {
    "name": "Test.txt"}
files = {
    'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
    'file': open("./Test.txt", "rb")}
r = requests.post(
    "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
    headers=headers,
    files=files)

print(r.text)
os.remove('Test.txt')

How can I fix this?

CodePudding user response:

I will assume you are running on Windows, because on that operating system you cannot delete a file if there is any file handle open on it anywhere, and that's your problem here.

You have opened a file handle to Test.txt and stored in in files["file"], and you need to close it before you can delete the file.

So this should solve your issue:

files["file"].close()
os.remove('Test.txt')
  • Related