Get list of files and folders in Google Drive storage using Python

Get list of files and folders in Google Drive storage using Python

To interact with Google Drive using Python, you can utilize the Google Drive API. Here's a step-by-step guide to obtaining a list of files and folders in your Google Drive:

Step 1: Set up Google Drive API

  1. Visit the Google Developer Console.
  2. Create a new project.
  3. Enable the Google Drive API for this project.
  4. Go to the 'Credentials' tab and click 'Create Credentials'. Choose 'OAuth 2.0 Client ID'.
  5. Select 'Desktop App' and create.
  6. Download the generated credentials.json file.

Step 2: Install Required Python Libraries

You'll need the google-auth, google-auth-oauthlib, google-auth-httplib2, and google-api-python-client packages.

pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client 

Step 3: Python Code to List Files & Folders

import pickle import os from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from google.auth.transport.requests import Request # Initialize the Drive v3 API SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] creds = None # Load existing credentials if they exist if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no valid credentials, 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) with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('drive', 'v3', credentials=creds) # Call the Drive API results = service.files().list(pageSize=1000, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') else: print('Files and Folders:') for item in items: print(f"{item['name']} ({item['id']})") 

Run the above script. On the first run, it will open a new page in your default web browser, asking for permissions. Once you grant them, it will store a token.pickle file so you won't have to authenticate every time.

This script will retrieve and display up to 1000 files/folders from your Google Drive. Adjust the pageSize parameter as needed. The API has a limit on how many files it can retrieve in one request. If you have more files, you'll have to implement pagination using the nextPageToken in the response.


More Tags

autoit twitter-bootstrap-2 token wcf-web-api file-rename systemctl drupal updating scikit-image onbeforeunload

More Programming Guides

Other Guides

More Programming Examples