I’m trying to upload a .txt file to Google Drive using Python and need to get a URL that opens directly in Google Docs editor instead of the preview mode.
Here’s my current upload function:
def create_document(self, doc_name, file_path, parent_folder, existing_id=None, content_type='text/plain'):
upload_media = MediaFileUpload(
file_path, mimetype=content_type, resumable=True)
try:
if existing_id is None:
doc_metadata = {
"name": doc_name,
"parents": [parent_folder]
}
result = self.service.files().create(
body=doc_metadata,
media_body=upload_media,
fields='id').execute()
existing_id = result.get('id')
else:
doc_metadata = {"name": doc_name}
self.service.files().update(
body=doc_metadata,
removeParents='root',
media_body=upload_media,
fileId=existing_id).execute()
drive_url = 'https://drive.google.com/open?id=' + existing_id
return doc_name, existing_id, drive_url
The problem is this returns a URL that shows the file in Google Drive’s preview mode. Users have to manually click “Open with Google Docs” to start editing.
I want to generate a URL that opens the document directly in Google Docs editing interface. The Google Docs URLs look completely different from Drive URLs. Is there a way to get the direct editing link programmatically after uploading?