Skip to content

Instantly share code, notes, and snippets.

@pythoninthegrass
Created August 23, 2024 19:11
Show Gist options
  • Save pythoninthegrass/616e967c6c057240ad3f7fa6b210fcbd to your computer and use it in GitHub Desktop.
Save pythoninthegrass/616e967c6c057240ad3f7fa6b210fcbd to your computer and use it in GitHub Desktop.
Generate markdown files from TickTick backup CSV for use with Obsidian + Python Scripter plugin
#!/usr/bin/env python
import sys
import csv
import re
from pathlib import Path
python_script = Path(sys.argv[0])
vault_path = Path(sys.argv[1] if len(sys.argv) > 1 else "../../..").resolve()
file_path = Path(sys.argv[2] if len(sys.argv) > 2 else ".").resolve()
inbox = Path(sys.argv[3] if len(sys.argv) > 3 else vault_path / "Inbox").resolve()
abs_file_path = (vault_path / file_path).resolve()
csv_file = Path(sys.argv[4] if len(sys.argv) > 4 else abs_file_path / "ticktick_backup_20240823.csv").resolve()
def sanitize_filename(filename):
"""
Convert forward and backslashes to underscores
and remove any other invalid characters
"""
# Replace forward and backslashes with underscores
filename = re.sub(r'[/\\]', '_', filename)
# Remove any other characters that are invalid in file names
filename = re.sub(r'[<>:"|?*]', '', filename)
return filename.strip()
def extract_title_and_content(csv_file):
"""
extract title and content from a ticktick csv file
see: https://help.ticktick.com/articles/7055781405648748544
"""
with csv_file.open('r', newline='') as file:
csv_reader = csv.DictReader(file)
items = []
for row in csv_reader:
items.append({
'title': row['Title'],
'content': row['Content']
})
return items
def create_markdown_file(item, file_path):
"""
create a markdown file with only the content
if it doesn't already exist
"""
sanitized_title = sanitize_filename(item['title'])
file_name = sanitized_title + ".md"
file = file_path / file_name
if not file.exists():
file.write_text(item['content'])
return file
else:
return None
def main():
# create the inbox directory if it doesn't exist
if not inbox.exists():
inbox.mkdir()
# extract the title and content from the csv file
extracted_items = extract_title_and_content(csv_file)
# create markdown files
for item in extracted_items:
created_file = create_markdown_file(item, inbox)
if created_file:
print(f"Markdown file created: {created_file}")
else:
print(f"File already exists, skipped: {inbox / (sanitize_filename(item['title']) + '.md')}")
if __name__ == "__main__":
main()
@pythoninthegrass
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment