15 Downloads a file or a folder from Google Drive
18 file_id (str): ID of the folder/file to download
19 path (str): Local path where file(s) will be downloaded
27 rel_path = full_path.split(
"/")[:-1]
28 rel_path =
"/".join(rel_path)
31 SCOPES = [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive.readonly",
32 "https://www.googleapis.com/auth/drive.metadata.readonly",
"https://www.googleapis.com/auth/drive.appdata",
"https://www.googleapis.com/auth/drive.metadata",
33 "https://www.googleapis.com/auth/drive.photos.readonly"]
35 creds = Credentials.from_authorized_user_file(rel_path+
"/token.json", SCOPES)
36 service = build(
"drive",
"v3", credentials=creds)
38 file = service.files().get(fileId=file_id, fields=
"name, mimeType").execute()
39 file_name = file[
"name"]
40 mime_type = file[
"mimeType"]
41 new_path = os.path.join(path, file_name)
42 if mime_type ==
"application/vnd.google-apps.folder":
44 if not os.path.exists(new_path):
46 results = service.files().list(q=
"'{}' in parents".format(file_id), fields=
"nextPageToken, files(id, name)").execute()
47 items = results.get(
"files", [])
49 download_file_or_folder(item[
'id'], new_path)
52 request = service.files().get_media(fileId=file_id)
54 downloader = MediaIoBaseDownload(fh, request)
57 status, done = downloader.next_chunk()
58 print(
"Download %d%%." % int(status.progress() * 100))
61 with open(new_path,
"wb")
as f:
65 except HttpError
as error:
66 print(
"An error occurred: {}".format(error))
67 raise Exception(
"Some files can not be downloaded")