upload a zip file to google drive using python
- User
upload a zip file to google drive using python
- Assistant
Of course! Here is a complete, step-by-step guide to uploading a ZIP file to Google Drive using Python. This guide covers everything from setting up your Google API credentials to writing and running the script.
Step 1: Set Up Your Google Drive API Credentials
Before you can write any code, you need to authorize your application to access Google Drive.
-
Create a Google Cloud Project:
- Go to the Google Cloud Console.
- Create a new project (or select an existing one).
-
Enable the Google Drive API:
- In your project's dashboard, go to "APIs & Services" > "Library".
- Search for "Google Drive API" and click Enable.
-
Create OAuth 2.0 Credentials:
- Go to "APIs & Services" > "Credentials".
- Click + CREATE CREDENTIALS and select OAuth client ID.
- If prompted, configure the "OAuth consent screen".
- Choose External user type.
- Fill in the required fields (App name, User support email, Developer contact information). Don't worry about scopes for now. Click "Save and Continue" through the steps.
- Go back to the "Credentials" page. Click + CREATE CREDENTIALS > OAuth client ID again.
- Select Desktop app as the Application type.
- Give it a name (e.g., "Drive Uploader Script").
- Click Create.
-
Download Your Credentials:
- A pop-up will appear with your Client ID and Client Secret. Click the DOWNLOAD JSON button.
- Rename the downloaded file to
credentials.jsonand place it in the same directory where you will save your Python script. This file is secret, do not share it or commit it to a public repository!
Step 2: Install Necessary Python Libraries
You'll need the Google API Client Library for Python. Open your terminal or command prompt and install it using pip.
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlibStep 3: Prepare a Sample ZIP File
For this example, let's create a dummy file and zip it up.
- Create a text file named
sample.txtwith some content. - Create a zip file named
my_archive.zipcontainingsample.txt. You can do this manually or via the command line:# On Linux/macOS zip my_archive.zip sample.txt # On Windows (using PowerShell) Compress-Archive -Path "sample.txt" -DestinationPath "my_archive.zip"
Step 4: The Python Script
Now, create a Python file (e.g.,
upload_to_drive.py) in the same directory as yourcredentials.jsonandmy_archive.zip.This script will:
- Handle the authentication flow. The first time you run it, it will open a browser window for you to log in and grant permission. It will then save a
token.jsonfile so you don't have to log in every time. - Specify the file to be uploaded.
- Use the Google Drive API to perform the upload.
import os.path 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.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. # This scope allows the script to create new files in your Google Drive. SCOPES = ["https://www.googleapis.com/auth/drive.file"] def main(): """ Handles authentication and uploads a ZIP file to Google Drive. """ creds = None # The file token.json 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.json"): creds = Credentials.from_authorized_user_file("token.json", SCOPES) # 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: # This will use the 'credentials.json' file you downloaded flow = InstalledAppFlow.from_client_secrets_file( "credentials.json", SCOPES ) # This line opens a browser for you to authorize the app. creds = flow.run_local_server(port=0) # Save the credentials for the next run with open("token.json", "w") as token: token.write(creds.to_json()) try: # Build the Google Drive service service = build("drive", "v3", credentials=creds) # --- UPLOAD LOGIC --- # 1. Define the file to upload file_to_upload = "my_archive.zip" file_name_on_drive = "MyUploadedArchive.zip" # 2. Define the file metadata # This includes the name on Drive and the MIME type. # For a zip file, the MIME type is 'application/zip'. file_metadata = { "name": file_name_on_drive, # Optional: To upload to a specific folder, add its ID here. # "parents": ["YOUR_FOLDER_ID_HERE"] } # 3. Define the media body # This uses MediaFileUpload to handle the file content. media = MediaFileUpload(file_to_upload, mimetype="application/zip", resumable=True) # 4. Create the file on Google Drive # The 'fields' parameter specifies what information to get back about the created file. print(f"Uploading {file_to_upload} as '{file_name_on_drive}'...") file = ( service.files() .create(body=file_metadata, media_body=media, fields="id, name") .execute() ) print(f"File uploaded successfully!") print(f"File Name: {file.get('name')}") print(f"File ID: {file.get('id')}") except HttpError as error: print(f"An error occurred: {error}") if __name__ == "__main__": main()Step 5: How to Run the Script
-
Make sure your directory contains:
upload_to_drive.py(the script above)credentials.json(downloaded from Google Cloud Console)my_archive.zip(the file you want to upload)
-
Open your terminal or command prompt in that directory.
-
Run the script:
python upload_to_drive.py -
First Run: A new tab will open in your web browser.
- You will be asked to choose a Google Account.
- You will see a "Google hasn't verified this app" warning. This is normal because it's your own script. Click Advanced, then Go to [Your App Name] (unsafe).
- Grant the script permission to "See, create, and delete all of your Google Drive files".
- Once you approve, the page will say "The authentication flow has completed." You can close the tab.
- The script will continue running in your terminal and upload the file. A
token.jsonfile will be created in your directory.
-
Subsequent Runs: The script will find the
token.jsonfile and use it to authenticate automatically without opening a browser. It will immediately proceed to upload the file.
(Optional) How to Upload to a Specific Folder
If you want the file to appear inside a specific folder in your Google Drive, follow these steps:
-
Find the Folder ID:
- Go to your Google Drive in the browser and open the folder you want to upload to.
- Look at the URL in the address bar. The ID is the long string of characters at the end.
https://drive.google.com/drive/folders/1a2b3c4d5e6f7g8h9i0j_kL- In this example, the Folder ID is
1a2b3c4d5e6f7g8h9i0j_kL.
-
Modify the Script:
- In the
upload_to_drive.pyscript, find thefile_metadatadictionary. - Uncomment the
parentsline and replace"YOUR_FOLDER_ID_HERE"with your actual folder ID.
# Change this part of the script: file_metadata = { "name": file_name_on_drive, # To upload to a specific folder, add its ID here. "parents": ["1a2b3c4d5e6f7g8h9i0j_kL"] } - In the
Now when you run the script, the ZIP file will be uploaded directly into that folder.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.