Skip to content
Advertisement

Google drive API Python – how to set a destination to files that are downloaded with the api

i am downloading the files inside a folder in drive, and i wanted to store them also in a local folder in the same location where my python script is, instead that saving them unorderer without a folder my current code is here:

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import io
from googleapiclient.http import MediaIoBaseDownload

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive']

def main():
 
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('drive', 'v3', credentials=creds)

    # Call the Drive v3 API
    
    # supose that 213fkrjbk324fnvbknfd is the folder id

    query = "'213fkrjbk324fnvbknfd' in parents"
 
    response = service.files().list(q=query,
                                spaces='drive',
                                fields='files(id, name, parents)').execute()
    
    for document in response['files']:
        #file_id = service.files.list()
        request = service.files().get_media(fileId=document['id'])
        fh = io.FileIO('filename.extension', mode='wb')
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(document['name'])
            print ("Download %d%%." % int(status.progress() * 100))
            print("-------------------------------------------------------------------------------------")

   

if __name__ == '__main__':
    main()
    
    

when i run this code the console shows the download 100% string but i cant find the files neither on the location of my script nor on other location of the local storage.

Advertisement

Answer

The downloaded data is still stored in RAM. This copies the data to the folder where your python file is.

while done is False:
    [....]

# This is where it downloads the file
fh.seek(0)
with open('your_filename.pdf', 'wb') as f:
    shutil.copyfileobj(fh, f, length=131072)

If you are experiencing issues, I found this answer here.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement