Jie Jenn - 04-downloadFiles

4. Google Drive API in Python | Download Files

Part 0

00

This script is not working, Skip to delete file/folders than work on data analysis and scraping, save project to google drive with python

Part 1 - Import libraries/module and start script

01

Get the id for the files from drive double click on the file's name, then opening into a new window

02

The fles id is in the URL before view

03

Get the file id for the excel file seen in previous lesson 03-uploadFiles and put them into a list file_ids

You also need to import 3 modules to download files from drive

import os
import io
from googleapiclient.http import MediaIoBaseDownload
from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'

SCOPES = ['https://www.googleapis.com/auth/drive']
service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)

file_ids = ['1fF3WBDA8l9Mw40_Xf_8Ftgf9N-cgs2wW', '1M_TC8OjNl1TgE44BXo5hTy-BjDJio7Yq']

04

Make a list for file_name (** you have the option to rename files here)

import os
import io
from googleapiclient.http import MediaIoBaseDownload
from googleServiceCreate import create_service
CLIENT_SECRET = 'credentials.json'
API_NAME = 'drive'
API_VERSION = 'v3'

SCOPES = ['https://www.googleapis.com/auth/drive']
service = create_service(CLIENT_SECRET,API_NAME,API_VERSION,SCOPES)


file_ids = ['1fF3WBDA8l9Mw40_Xf_8Ftgf9N-cgs2wW', '1M_TC8OjNl1TgE44BXo5hTy-BjDJio7Yq']
file_name = ['excelExample.xlsx','fall.jpeg']

                                

Part 2 - script

01

zip and loop through file_ids and file_names. Provide the file_id to the method files().get_media() parameter fileId parameters, on a a request object

file_ids = ['1fF3WBDA8l9Mw40_Xf_8Ftgf9N-cgs2wW', '1M_TC8OjNl1TgE44BXo5hTy-BjDJio7Yq']
file_names = ['excelExample.xlsx','fall.jpeg']

for file_id, file_name in zip(file_ids,file_names):
    request = service.files().get_media(fileId=file_id)
                                

02

I don't get this fully, us io module's BytesIO() and put it in a fh variable, then, assign it to a MediaIoBaseDownload along with the request in a output

fh = io.BytesIO()
download = MediaIoBaseDownload(fd=fh, request= request )
                                

03

make a while loop for the download MediaIoBaseDownload object. This return a tuple, use the status to monitor the progress with a f string or format

progress() * 100 converts it to a percentage


                                

04

We can seek throught the fh variable and write it to a file