This blog article shows you how to upload file to Google Drive using Python.
To upload a file to Google Drive using Python, you’ll need to use the Google Drive API. Here’s a step-by-step guide on how to achieve this:
1. Set up a Google Cloud Project and enable the Google Drive API:
– Go to the [Google Cloud Console](https://console.cloud.google.com/).
– Create a new project (or select an existing one).
– Enable the Google Drive API for your project.
– Create OAuth 2.0 credentials for a Desktop application.
– Download the `credentials.json` file.
2. Install required libraries:
You will need the `google-auth`, `google-auth-oauthlib`, `google-auth-httplib2`, and `google-api-python-client` libraries. You can install them using pip:
pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client
3. Write the Python script to upload the file:
Below is a sample Python script that handles the authentication process and uploads a file to Google Drive.
from __future__ import print_function
import os
import pickle
import io
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
# If modifying these SCOPES, delete the file token.pickle.
SCOPES = [‘https://www.googleapis.com/auth/drive.file’]
def main():
“””Shows basic usage of the Drive v3 API.
Uploads a file to 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)
service = build(‘drive’, ‘v3’, credentials=creds)
# File you want to upload
file_path = ‘your_file.txt’ # Update this with the path to your file
file_metadata = {‘name’: os.path.basename(file_path)}
media = MediaFileUpload(file_path, mimetype=’text/plain’)
# Upload the file
file = service.files().create(body=file_metadata,
media_body=media,
fields=’id’).execute()
print(‘File ID: %s’ % file.get(‘id’))
if __name__ == ‘__main__’:
main()
Explanation:
Also: Where to get the ClientId and ClientSecret for Google API
1. Import necessary libraries: The script imports the required libraries for handling authentication and making requests to the Google Drive API.
2. Define SCOPES: Scopes determine the level of access you need. `’https://www.googleapis.com/auth/drive.file’` allows read and write access to the files created or opened by the app.
3. Handle credentials: The script checks if there is an existing token (`token.pickle`). If not, it goes through the OAuth 2.0 flow to generate one.
4. Build the Drive API service: Using the credentials, it creates a service object for the Drive API.
5. File metadata and upload: The script sets up the file metadata (like the file name) and uploads the file using `MediaFileUpload`.
Running the Script:
– Make sure your `credentials.json` file is in the same directory as your script.
– Replace `’your_file.txt’` with the path to the file you want to upload.
– Run the script using Python.
This will upload the specified file to your Google Drive and print the file ID upon successful upload.
Source code download: https://github.com/chanmmn/python/tree/main/2024/UploadFileGoogleDrive?WT.mc_id=DP-MVP-36769
Reference: https://developers.google.com/docs/api/quickstart/python?WT.mc_id=DP-MVP-36769
https://github.com/googleapis/google-api-python-client?WT.mc_id=DP-MVP-36769