I’m using Google Colab and need help with something specific. After I create a file and save it to my mounted Google Drive, I want to get its shareable URL programmatically.
Here’s what I’m doing:
from google.colab import drive
drive.mount('/content/gdrive')
import os
os.chdir('/content/gdrive/My Drive/')
# Create and write to file
with open('sample_document.txt', 'w') as file_handler:
file_handler.write('Test content')
# Need to get shareable URL for sample_document.txt at this point
Is there a way to automatically retrieve the sharing link for this newly created file without manually going to Google Drive interface? I need this URL to be accessible from my Python script.
Had this exact problem a few months ago automating reports for my team. You’ll want the Google Drive API - here’s what works:
After Colab creates your file, authenticate with Drive API and search by filename to grab the file ID. Then update sharing permissions and build your shareable URL. The catch? Files created through mounted drive don’t auto-enable sharing, so you’ve got to do it manually.
Heads up - there’s usually a delay between when your file shows up in mounted drive vs when Drive API can find it. I throw in a small sleep or retry to handle the timing.
Adds maybe 10-15 lines but runs solid once you get it dialed in.
totally feel ya! ran into this too. u need to use the Drive API, but yeah, files from Colab don’t sync fast. i added time.sleep(5) after creating the file, then used the API to search for the file ID. set permissions to ‘anyone with link’ and build the URL. quick and dirty but it gets the job done!
Google Drive API is definitely the way to go. I’ve done similar automation and you need to get authentication right first - use service account credentials or OAuth depending on what you’re building. Here’s something that tripped me up: file indexing delays. When you create files through the mounted filesystem, Google’s backend takes time to process them before they show up in API calls. I just poll every few seconds until the file appears in search results. You’ll also need to set sharing permissions through the Drive API’s permissions endpoint. Files created in Colab stay private by default - you have to change that programmatically. After that, building the shareable URL is easy with the file ID.