How to download specific Google Drive folder using Python?

后端 未结 4 568
面向向阳花
面向向阳花 2020-12-06 15:18

I\'m trying to download specific folders from Google Drive.

I tried this example http://www.mwclearning.com/?p=1608 but its download all the files from G-Drive.

4条回答
  •  无人及你
    2020-12-06 16:15

    Here's just the code that deals specifically with downloading a folder recursively.

    I've tried to keep it to-the-point, omitting code that's described in tutorials already. I expect you to already have the ID of the folder that you want to download.

    The part elif not itemType.startswith('application/'): has the purpose of skipping any Drive-format documents. However, the check is overly-simplistic, so you might want to improve it or remove it.

    from __future__ import print_function
    import pickle
    import os.path
    import io
    from googleapiclient.discovery import build
    from googleapiclient.http import MediaIoBaseDownload
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    
    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
    
    def main():
        """Based on the quickStart.py example at
        https://developers.google.com/drive/api/v3/quickstart/python
        """
        creds = getCredentials()
        service = build('drive', 'v3', credentials=creds)
        
        folderId = ""
        destinationFolder = ""
        downloadFolder(service, folderId, destinationFolder)
    
    
    def downloadFolder(service, fileId, destinationFolder):
        if not os.path.isdir(destinationFolder):
            os.mkdir(path=destinationFolder)
    
        results = service.files().list(
            pageSize=300,
            q="parents in '{0}'".format(fileId),
            fields="files(id, name, mimeType)"
            ).execute()
    
        items = results.get('files', [])
    
        for item in items:
            itemName = item['name']
            itemId = item['id']
            itemType = item['mimeType']
            filePath = destinationFolder + "/" + itemName
    
            if itemType == 'application/vnd.google-apps.folder':
                print("Stepping into folder: {0}".format(filePath))
                downloadFolder(service, itemId, filePath) # Recursive call
            elif not itemType.startswith('application/'):
                downloadFile(service, itemId, filePath)
            else:
                print("Unsupported file: {0}".format(itemName))
    
    
    def downloadFile(service, fileId, filePath):
        # Note: The parent folders in filePath must exist
        print("-> Downloading file with id: {0} name: {1}".format(fileId, filePath))
        request = service.files().get_media(fileId=fileId)
        fh = io.FileIO(filePath, mode='wb')
        
        try:
            downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)
    
            done = False
            while done is False:
                status, done = downloader.next_chunk(num_retries = 2)
                if status:
                    print("Download %d%%." % int(status.progress() * 100))
            print("Download Complete!")
        finally:
            fh.close()
    

提交回复
热议问题