Upload File to Google Drive using Python

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()

clip_image002

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

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress (http://www.pcworld.com/article/206455/Microsoft_Live_Spaces_Moves_to_WordPress_An_FAQ.html) till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.