Created
October 30, 2021 22:56
-
-
Save vgaraujov/47ef44430fdbcc95dcb6c87233c3ef92 to your computer and use it in GitHub Desktop.
A PyDrive client-based function to walk through all subfolders of a gdrive folder and download the folder structure with all files inside. Forked from https://stackoverflow.com/a/58207188/13521099
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| def drive_download(drive, fid): | |
| MIMETYPES = { | |
| # Drive Document files as MS dox | |
| 'application/vnd.google-apps.document': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', | |
| # Drive Sheets files as MS Excel files. | |
| 'application/vnd.google-apps.spreadsheet': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', | |
| # Drive presentation as MS pptx | |
| 'application/vnd.google-apps.presentation': 'application/vnd.openxmlformats-officedocument.presentationml.presentation' | |
| # see https://developers.google.com/drive/v3/web/mime-types | |
| } | |
| EXTENSTIONS = { | |
| 'application/vnd.google-apps.document': '.docx', | |
| 'application/vnd.google-apps.spreadsheet': '.xlsx', | |
| 'application/vnd.google-apps.presentation': '.pptx' | |
| } | |
| f = open("log_drive_download.txt","w+") | |
| folder_id = fid | |
| root = 'drive_download' | |
| os.mkdir(root) | |
| def escape_fname(name): | |
| return name.replace('/','_') | |
| def search_folder(folder_id, root): | |
| file_list = drive.ListFile({'q': "'%s' in parents and trashed=false" % folder_id}).GetList() | |
| for file in file_list: | |
| # print('title: %s, id: %s, kind: %s' % (file['title'], file['id'], file['mimeType'])) | |
| # print(file) | |
| if file['mimeType'].split('.')[-1] == 'folder': | |
| foldername = escape_fname(file['title']) | |
| create_folder(root,foldername) | |
| search_folder(file['id'], '{}{}/'.format(root,foldername)) | |
| else: | |
| download_mimetype = None | |
| filename = escape_fname(file['title']) | |
| filename = '{}{}'.format(root,filename) | |
| try: | |
| print('DOWNLOADING:', filename) | |
| if file['mimeType'] in MIMETYPES: | |
| download_mimetype = MIMETYPES[file['mimeType']] | |
| file.GetContentFile(filename+EXTENSTIONS[file['mimeType']], mimetype=download_mimetype) | |
| else: | |
| file.GetContentFile(filename) | |
| f.write('DOWNLOADED: ' +filename+'\n') | |
| except: | |
| print('FAILED:', filename) | |
| f.write('FAILED: ' +filename+'\n') | |
| def create_folder(path,name): | |
| os.mkdir('{}{}'.format(path,escape_fname(name))) | |
| search_folder(folder_id,root+'/') | |
| f.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment