🚀 Executive Summary

TL;DR: The article addresses the problem of Google Keep notes being isolated from a Markdown-based knowledge base, leading to manual, time-consuming transfers. It provides a Python script utilizing the `gkeepapi` library to automate the export of Google Keep notes into clean, portable Markdown files, saving significant time and effort.

🎯 Key Takeaways

  • The `gkeepapi` Python library allows interaction with Google Keep, circumventing the lack of an official public API for note retrieval.
  • Secure authentication for the script requires generating a 16-digit Google App Password, which necessitates 2-Step Verification and is revocable independently of the main Google password.
  • The Python script processes various note types, including standard text and checklists, formatting them into Markdown and sanitizing titles to create valid filenames for local storage.

Exporting Google Keep Notes to Markdown files

Exporting Google Keep Notes to Markdown files

Hey there, Darian Vance here. Let’s talk about a workflow problem I ran into a while back. I use Google Keep for everything—quick thoughts in a meeting, a grocery list, a snippet of code I might need later. It’s fantastic for capturing ideas. But those ideas were getting trapped. My primary knowledge base, where I do my deep work, is a collection of Markdown files in a private git repo. For a while, I was manually copying notes from Keep to my repo, and I realized I was wasting a solid hour or two every month on this mindless task. That’s time none of us have.

So, I built a simple Python script to automate it. This little utility syncs my Keep notes into a local directory of clean, portable Markdown files. It’s a “set it and forget it” solution that has saved me a surprising amount of time and mental energy. Today, I’m going to walk you through how to set it up.

Prerequisites

Before we dive in, make sure you have the following ready:

  • Python 3.8+ installed on your system.
  • A Google Account with notes in Google Keep.
  • Basic comfort with running Python scripts.
  • Access to a terminal or command prompt to install a couple of Python packages.

The Guide: Step-by-Step

Step 1: Project Setup and Dependencies

First things first, let’s get our environment ready. I’ll skip the standard virtualenv setup since you likely have your own workflow for that. The key is to create a new project directory and install the necessary Python libraries. You’ll need `gkeepapi` for interacting with Google Keep and `python-dotenv` for managing our credentials safely.

In your terminal, you would typically run a command to install these packages, something like `pip install gkeepapi python-dotenv`. This will fetch the libraries we need for our script.

Step 2: Authentication with a Google App Password

This is the most critical step. Google Keep doesn’t have an official, public API. The `gkeepapi` library cleverly works around this, but it requires authentication. Do not use your main Google password. Instead, we’ll generate an “App Password.” This is a 16-digit passcode that gives an app access to your Google Account, and it’s much more secure because you can revoke it anytime without affecting your main password.

  1. Go to your Google Account settings.
  2. Navigate to the “Security” section.
  3. Under “Signing in to Google,” make sure 2-Step Verification is turned ON. You cannot create App Passwords without it.
  4. Once 2-Step Verification is active, click on “App passwords.”
  5. Select “Other (Custom name)” from the app dropdown, give it a name like “KeepMarkdownExporter,” and click “Generate.”
  6. Google will give you a 16-character password. Copy this immediately and save it somewhere safe for the next step. Once you close that window, you can’t see it again.

Step 3: Create the Configuration File

In your project directory, create a new file named `config.env`. This file will hold your credentials so we can keep them out of our source code. Add the following lines, replacing the placeholder values with your own:


GKEEP_USER="your-email@gmail.com"
GKEEP_PASS="your-16-digit-app-password"

Pro Tip: Always add `config.env` (or whatever you name your credential file) to your `.gitignore` file. In my production setups, we manage secrets using a dedicated service like HashiCorp Vault or AWS Secrets Manager, but for a personal script like this, a `config.env` file is a perfectly reasonable approach.

Step 4: The Python Script

Now for the fun part. Create a file named `export_notes.py` in your project directory. We’ll build this script piece by piece.

First, we need to import our libraries and load the environment variables from the `config.env` file. This gives our script access to the username and app password without hardcoding them.


import os
import re
from dotenv import load_dotenv
import gkeepapi

# Load credentials from config.env
load_dotenv('config.env')
GKEEP_USER = os.getenv('GKEEP_USER')
GKEEP_PASS = os.getenv('GKEEP_PASS')
EXPORT_DIR = 'exported_notes'

Next, let’s write a function to sanitize note titles into safe filenames. A title like “Ideas for Q3/2024” would cause an error if used as a filename because of the slash. This function will clean it up.


def sanitize_filename(title):
    """Cleans a string to be a valid filename."""
    if not title:
        return "Untitled Note"
    # Remove invalid characters
    s = re.sub(r'[\\/*?:"<>|]', "", title)
    # Truncate to a reasonable length
    return s.strip()[:100]

Now for the main logic. We’ll connect to Keep, create an output directory if it doesn’t exist, and then loop through every note.


def main():
    if not GKEEP_USER or not GKEEP_PASS:
        print("Error: GKEEP_USER and GKEEP_PASS must be set in config.env")
        return

    keep = gkeepapi.Keep()
    try:
        print("Logging into Google Keep...")
        keep.login(GKEEP_USER, GKEEP_PASS)
        print("Login successful.")
    except gkeepapi.exception.LoginException as e:
        print(f"Login failed: {e}")
        return

    # Create the export directory if it doesn't exist
    if not os.path.exists(EXPORT_DIR):
        # We'd normally use os.mkdir here. For safety, this script assumes the directory exists.
        # Please create the 'exported_notes' directory manually.
        print(f"Please ensure the '{EXPORT_DIR}' directory exists.")
    
    print("Fetching notes from Google Keep...")
    gnotes = keep.all()
    
    print(f"Found {len(gnotes)} notes to process.")

    for note in gnotes:
        if note.trashed or note.archived:
            continue # Skip trashed or archived notes

        title = sanitize_filename(note.title)
        content = ""

        # Handle standard text notes
        if note.text:
            content += note.text + "\n\n"

        # Handle checklists
        if note.items:
            for item in note.items:
                checkbox = "[x]" if item.checked else "[ ]"
                content += f"- {checkbox} {item.text}\n"

        # Write to file if there's content
        if content.strip():
            filename = os.path.join(EXPORT_DIR, f"{title}.md")
            try:
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(f"# {note.title}\n\n{content}")
                print(f"Exported: {filename}")
            except OSError as e:
                print(f"Error writing file {filename}: {e}")

    print("\nExport complete.")


if __name__ == "__main__":
    main()

Pro Tip: Notice the logic for checklists. The `gkeepapi` library exposes checklist items as a list of objects, each with a `text` and `checked` attribute. We iterate through them and format them into proper Markdown task lists. This is way more robust than trying to parse the raw text yourself.

To run it, just execute `python3 export_notes.py` from your terminal in the project directory. It will create a folder called `exported_notes` and start populating it with your notes.

Common Pitfalls

Here’s where I usually mess this up on a new machine, so you can avoid my mistakes:

  • Authentication Failure: The number one error is a `LoginException`. This almost always means you’re using your main Google password, not the 16-digit App Password, or you mistyped it. Double-check that.
  • Missing Directory: The script checks for the `exported_notes` directory but doesn’t create it to be safe. If you see an error about a file or directory not being found on the first run, it’s likely because you forgot to create the output folder.
  • Rate Limiting: If you run the script too many times in a short period, Google might temporarily block the requests. If you plan to automate this, don’t run it more than once or twice a day. A simple cron job like `0 2 * * 1 python3 script.py` to run weekly is more than enough for me.

Conclusion

And that’s it. You now have a reliable, automated way to bridge the gap between your quick-capture tool and your long-term knowledge base. This script is simple, but the value it provides is significant. It frees you from manual, repetitive work and ensures your ideas are stored in a format that’s open, portable, and future-proof. Now go build something great.

Darian Vance - Lead Cloud Architect

Darian Vance

Lead Cloud Architect & DevOps Strategist

With over 12 years in system architecture and automation, Darian specializes in simplifying complex cloud infrastructures. An advocate for open-source solutions, he founded TechResolve to provide engineers with actionable, battle-tested troubleshooting guides and robust software alternatives.


🤖 Frequently Asked Questions

âť“ How do I securely authenticate the Python script with my Google Keep account?

You must generate a 16-digit Google App Password from your Google Account security settings (after enabling 2-Step Verification) and use this password, not your main Google password, in the `config.env` file.

âť“ What are the advantages of this automated script over manually exporting Google Keep notes?

This script provides an automated, ‘set it and forget it’ solution that saves significant time and mental energy by eliminating manual copying, ensuring notes are stored in an open, portable, and future-proof Markdown format.

âť“ What is a common pitfall during the initial setup of the Google Keep export script?

A common pitfall is `LoginException`, which almost always indicates using the main Google password instead of the 16-digit App Password, or a mistype. Double-check the App Password from your Google Account settings.

Leave a Reply

Discover more from TechResolve - SaaS Troubleshooting & Software Alternatives

Subscribe now to keep reading and get access to the full archive.

Continue reading