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')}")