If you don't have a markdown file: create one using the text below:
markdown_text = "This is markdown. \n\n # Header 1 \n\n ## Header 2 \n\n plain text"
with open("test.md", "w", encoding="utf-8") as f:
f.write(markdown_text)
upload
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
FILE_NAME = "test"
media = MediaFileUpload(f"{FILE_NAME}.md", mimetype="text/markdown", resumable=True)
drive_service = build("drive", "v3", credentials=credentials) # obtaining credentials is not covered here
doc = (
drive_service.files()
.create(
body={"name": FILE_NAME, "mimeType": "application/vnd.google-apps.document"},
media_body=media,
fields="id, webViewLink",
)
.execute()
)
shareable_link = doc.get("webViewLink")
print(f"{FILE_NAME}.md uploaded to: {doc.get('webViewLink')}")
If you don't have a txt file: create one using the text below:
FILE_NAME = "test"
test_text = "row 1\nrow 2"
with open(f"{FILE_NAME}.txt", "w", encoding="utf-8") as f:
f.write(test_text)
most text files don't have a header so it's good to add one and easier to do on the txt file than the Google Sheets API:
with open(f"{FILE_NAME}.txt", "r") as f:
original_content = f.read()
with open(f"{FILE_NAME}2.txt", "w", encoding="utf-8") as f:
f.write("data\n")
f.write(original_content)
upload (not setting mimeType to csv will ensure it's uploaded to a Google sheet and not a Google doc
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
FILE_NAME = "test"
media = MediaFileUpload(f"{FILE_NAME}2.txt", mimetype="text/csv", resumable=True)
drive_service = build("drive", "v3", credentials=credentials) # obtaining credentials is not covered here
sheet = (
drive_service.files()
.create(
body={"name": FILE_NAME, "mimeType": "application/vnd.google-apps.spreadsheet"},
media_body=media,
fields="id, webViewLink",
)
.execute()
)
shareable_link = doc.get("webViewLink")
print(f"{FILE_NAME}.txt uploaded to: {sheet.get('webViewLink')}")
# /// script
# requires-python = ">=3.14"
# dependencies = [
# "google-api-python-client>=2.187.0",
# "google-auth-oauthlib>=1.2.3",
# ]
# ///
import time
import io
from pathlib import Path
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 MediaIoBaseUpload
SCOPES = ["https://www.googleapis.com/auth/drive.file"]
CREDS_FILE = Path.home() / ".google_client_secret.json"
TOKEN_FILE = Path.home() / ".token.json"
def get_creds():
creds = None
if TOKEN_FILE.exists():
creds = Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
if not CREDS_FILE.exists():
raise FileNotFoundError(
f"Client secrets not found at {CREDS_FILE.absolute()}"
)
flow = InstalledAppFlow.from_client_secrets_file(str(CREDS_FILE), SCOPES)
creds = flow.run_local_server(port=0)
TOKEN_FILE.write_text(creds.to_json())
return creds
def main():
markdown_text = "This is markdown. \n\n # Header 1 \n\n ## Header 2 \n\n plain text"
file_name = "test"
try:
service = build("drive", "v3", credentials=get_creds())
fh = io.BytesIO(markdown_text.encode("utf-8"))
media = MediaIoBaseUpload(fh, mimetype="text/markdown", resumable=True)
print("Uploading...")
file_meta = {
"name": file_name,
"mimeType": "application/vnd.google-apps.document",
}
doc = (
service.files()
.create(body=file_meta, media_body=media, fields="id, webViewLink")
.execute()
)
file_id = doc.get("id")
print(f"Success! ID: {file_id}\nLink: {doc.get('webViewLink')}")
print("Deleting in 5 seconds...")
time.sleep(5)
service.files().delete(fileId=file_id).execute()
print("Done.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()