Python: download files from google drive using url

前端 未结 9 1368
眼角桃花
眼角桃花 2020-11-27 11:51

I am trying to download files from google drive and all I have is the drive\'s URL.

I have read about google API that talks about some drive_service and

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 12:44

    # Importing [PyDrive][1] OAuth
    from pydrive.auth import GoogleAuth
    
    def download_tracking_file_by_id(file_id, download_dir):
        gauth = GoogleAuth(settings_file='../settings.yaml')
        # Try to load saved client credentials
        gauth.LoadCredentialsFile("../credentials.json")
        if gauth.credentials is None:
            # Authenticate if they're not there
            gauth.LocalWebserverAuth()
        elif gauth.access_token_expired:
            # Refresh them if expired
            gauth.Refresh()
        else:
            # Initialize the saved creds
            gauth.Authorize()
        # Save the current credentials to a file
        gauth.SaveCredentialsFile("../credentials.json")
    
        drive = GoogleDrive(gauth)
    
        logger.debug("Trying to download file_id " + str(file_id))
        file6 = drive.CreateFile({'id': file_id})
        file6.GetContentFile(download_dir+'mapmob.zip')
        zipfile.ZipFile(download_dir + 'test.zip').extractall(UNZIP_DIR)
        tracking_data_location = download_dir + 'test.json'
        return tracking_data_location
    

    The above function downloads the file given the file_id to a specified downloads folder. Now the question remains, how to get the file_id? Simply split the url by id= to get the file_id.

    file_id = url.split("id=")[1]
    

提交回复
热议问题