6

I would like to download a file in google drive to my system,using google drive api. How can i implement this ?

according to example given at https://developers.google.com/drive/v2/reference/files/get#examples

def print_file(service, file_id):

 """Print a file's metadata.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to print metadata for.
  """
  try:
    file = service.files().get(fileId=file_id).execute()

    print 'Title: %s' % file['title']
    print 'MIME type: %s' % file['mimeType']
  except errors.HttpError, error:
    print 'An error occurred: %s' % error


def download_file(service, drive_file):
  """Download a file's content.

  Args:
    service: Drive API service instance.
    drive_file: Drive File instance.

  Returns:
    File's content if successful, None otherwise.
  """
  download_url = drive_file.get('downloadUrl')
  if download_url:
    resp, content = service._http.request(download_url)
    if resp.status == 200:
      print 'Status: %s' % resp
      return content
    else:
      print 'An error occurred: %s' % resp

I am able to find the file , But how can i download it locally to my machine ?

General4077
  • 435
  • 1
  • 8
  • 17
Dhanya M
  • 81
  • 1
  • 1
  • 8
  • Does this answer your question? [How to download a Google Drive file using Python and the Drive API v3](https://stackoverflow.com/questions/60111361/how-to-download-a-google-drive-file-using-python-and-the-drive-api-v3) – RayB Aug 24 '20 at 18:37

2 Answers2

3

just write the content variable to a file instead of returning the content

fo = open("foo.jpg", "wb")
fo.write(content)
fo.close()
Akhil Nadh PC
  • 574
  • 1
  • 7
  • 24
2

I think you should probably check out this:

http://pythonhosted.org/PyDrive/

The code seems like it is easier

# Initialize GoogleDriveFile instance with file id.
file6 = drive.CreateFile({'id': file5['id']})
file6.GetContentFile('catlove.png') # Download file as 'catlove.png'.

# Initialize GoogleDriveFile instance with file id.
file7 = drive.CreateFile({'id': file4['id']})
content = file7.GetContentString()
# content: '{"firstname": "Claudio", "lastname": "Afshar"}'