| To obtain a Google Drive file list and download files using Python, you'll need to utilize the Google Drive API. First, create a Google Cloud Platform project and enable the Drive API. Then, download the Google Client Library for Python and authenticate your application using OAuth 2.0. Once authenticated, use the API's files.list method to retrieve a list of files and their metadata. For each file you wish to download, use the files.get method with the download parameter set to True to download the file's content to your local system. Handle the returned data accordingly, potentially saving files based on their names and/or IDs. Here is a Python script to list files on your Google Drive and download one of them using the Google Drive API. The script uses the google-auth, google-auth-oauthlib, and google-auth-httplib2 libraries along with the googleapiclient.discovery module. 
Step 1: Set Up the Google Drive API - Go to the Google Cloud Console.
- Create a new project or use an existing one.
- Enable the "Google Drive API" for your project.
- Create OAuth 2.0 credentials and download the
credentials.json file.
Step 2: Install Required Libraries pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2
Step 3: Python Script import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io
# Scopes for Google Drive
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
def authenticate():
"""
Authenticate and return a Google Drive service instance.
"""
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
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.json', 'w') as token:
token.write(creds.to_json())
return build('drive', 'v3', credentials=creds)
def list_files(service, page_size=10):
"""
List files in Google Drive.
"""
results = service.files().list(
pageSize=page_size, fields="nextPageToken, files(id, name)"
).execute()
items = results.get('files', [])
if not items:
print('No files found.')
return []
else:
print('Files:')
for item in items:
print(f"{item['name']} ({item['id']})")
return items
def download_file(service, file_id, file_name):
"""
Download a file from Google Drive.
"""
request = service.files().get_media(fileId=file_id)
file_path = os.path.join(os.getcwd(), file_name)
with io.FileIO(file_path, 'wb') as fh:
downloader = MediaIoBaseDownload(fh, request)
done = False
while not done:
status, done = downloader.next_chunk()
print(f"Download {int(status.progress() * 100)}%.")
print(f"File downloaded to {file_path}")
def main():
service = authenticate()
files = list_files(service)
if files:
# Select a file to download
file_id = files[0]['id'] # Replace with the desired file ID
file_name = files[0]['name']
download_file(service, file_id, file_name)
if __name__ == '__main__':
main()
Notes: - Save the
credentials.json file in the same directory as your script. - The script saves a
token.json file to cache credentials and avoid repeated logins. - Modify the
file_id to download a specific file. - You may need to adjust permissions if the file is private or shared. Ensure the Google Drive account used has access to the file.
|