In [ ]:
from __future__ import print_function
import httplib2
import inspect
import os
from apiclient import discovery
from apiclient import errors
import oauth2client
from oauth2client import client
from oauth2client import tools
In [ ]:
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly https://www.googleapis.com/auth/drive.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'
In [ ]:
def get_credentials():
"""Gets valid user credentials from storage.
Must run google_api_credentials.py from the command line first to set up credentials.
Returns:
Credentials, the obtained credential.
"""
credential_path = '../temp/.credentials/drive-python-quickstart.json'
store = oauth2client.file.Storage(credential_path)
return store.get()
In [ ]:
def get_children_ids(service, folder_id):
"""Print files belonging to a folder.
Args:
service: Drive API service instance.
folder_id: ID of the folder to print files from.
"""
page_token = None
all_children = []
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
children = service.children().list(folderId=folder_id, **param).execute()
child_items = children.get('items', [])
all_children.extend(child_items)
page_token = children.get('nextPageToken')
if not page_token:
break
except (errors.HttpError, error):
print('An error occurred: %s' % error)
break
return all_children
In [ ]:
def get_file_info(service, file_id):
try:
file = service.files().get(fileId=file_id).execute()
return [file["originalFilename"], file_id, file["fileSize"]]
except (errors.HttpError, error):
print('An error occurred: %s' % error)
In [ ]:
def list_files(folder_id):
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('drive', 'v2', http=http)
listing = []
children = get_children_ids(service, folder_id)
for child in children:
entry = get_file_info(service, child["id"])
listing.append(entry)
print(",".join(entry))
return listing
In [ ]:
def list_all_files(folders):
for folder_id in folders:
results = list_files(folder_id)
results = sorted(results, key=lambda entry:entry[0])
with open("folder_" + folder_id + ".csv", "w") as drive_files:
for entry in results:
print(",".join(entry), file=drive_files)
In [ ]:
folder_ids = [
"0B8WcbXogHveganEwc0ZCelN2Wmc",
"0B8WcbXogHvegWU1JVTJzSG1FSjQ",
"0B8WcbXogHvegOW1yVXVBeGItSzQ",
"0B8WcbXogHvegb2JZQmJwRnZzMnc",
"0B8WcbXogHvegZTA1dFU4MXptM1k",
"0B8WcbXogHvegRWFRNVBJUXZnczg",
"0B8WcbXogHvegMnIxOHR0ME1lUlE",
"0B8WcbXogHvegbnF2U1lQbUFCQW8",
"0B8WcbXogHvegTHNmX3pWMnZrVnc",
"0B8WcbXogHvegS0NMLTFyckFwYnM",
"0B8WcbXogHvegeVZPLW1reDlRV0E",
"0B8WcbXogHvegYjVCVkQ4ZXV4aU0"
]
list_all_files(folder_ids)
In [ ]: