Skip to content

Instantly share code, notes, and snippets.

@dewitt4
Created August 15, 2023 17:39
Show Gist options
  • Save dewitt4/6d7da78c89bbdb6478f9482d85bef534 to your computer and use it in GitHub Desktop.
Save dewitt4/6d7da78c89bbdb6478f9482d85bef534 to your computer and use it in GitHub Desktop.
Python function that uses the Google Drive API to search for files across a user's Google Drive
import os
import pickle
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these SCOPES, delete the token.pickle file.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
def authenticate_google_drive():
creds = None
# The file token.pickle stores the user's access and refresh tokens,
# and is created automatically when the authorization flow completes
# for the first time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def search_files(query):
creds = authenticate_google_drive()
service = build('drive', 'v3', credentials=creds)
try:
results = service.files().list(
q=query,
fields="nextPageToken, files(id, name)").execute()
files = results.get('files', [])
if not files:
print('No files found.')
else:
print('Files:')
for file in files:
print(f"{file['name']} ({file['id']})")
except Exception as e:
print(f'An error occurred: {e}')
if __name__ == '__main__':
search_query = "Your search query here" # Replace with your search query
search_files(search_query)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment