macOS

Экспорт заметок в файлы

Сохраняет заметки Apple Notes в HTML или текст с заголовками и датой изменения

Python macOS Продвинутый
Скачать export_notes.py
Описание

Что делает скрипт

Скрипт получает заметки через AppleScript, разбирает заголовок, дату изменения и HTML-тело. Каждая заметка сохраняется отдельным файлом с безопасным именем, совпадения получают числовой суффикс. Приватные заметки не отправляются в сеть, экспорт выполняется только локально.

Перед запуском
  • Может запустить Notes и запросить разрешение на автоматизацию.
  • Экспортированные файлы содержат содержимое заметок, храните их в приватном месте.
Запуск

Быстрый старт

python3 export_notes.py --output ~/Desktop/notes-export

Скачайте файл, откройте терминал в папке со скриптом и выполните команду. В Linux и macOS интерпретатор может называться python3, в Windows - python или py.

Примеры

Другие варианты

  • python3 export_notes.py --output ~/Desktop/notes-export
  • python3 export_notes.py --format txt --output ./notes
  • python3 export_notes.py --format html --force --output ./notes
Зависимости

Что понадобится

Python 3.10+ Только стандартная библиотека
macOS brew install python
Исходник

export_notes.py

#!/usr/bin/env python3
"""Экспорт заметок Apple Notes в HTML или текст."""
from __future__ import annotations

import argparse
import html
import json
import re
import subprocess
import sys
from html.parser import HTMLParser
from pathlib import Path

APPLESCRIPT = """
set output to ""
tell application "Notes"
    repeat with noteRef in notes
        set output to output & "@@NOTE@@" & linefeed
        set output to output & "TITLE:" & (name of noteRef) & linefeed
        set output to output & "MODIFIED:" & (modification date of noteRef as string) & linefeed
        set output to output & "BODY:" & (body of noteRef) & linefeed
    end repeat
end tell
return output
"""


class TextExtractor(HTMLParser):
    def __init__(self) -> None:
        super().__init__()
        self.parts: list[str] = []

    def handle_data(self, data: str) -> None:
        self.parts.append(data)

    def text(self) -> str:
        return "".join(self.parts)


def strip_html(value: str) -> str:
    parser = TextExtractor()
    parser.feed(value)
    text = html.unescape(parser.text())
    lines = [line.rstrip() for line in text.splitlines()]
    return "\n".join(line for line in lines if line.strip())


def safe_name(title: str) -> str:
    name = re.sub(r"[^\w\-. ]+", "_", title, flags=re.UNICODE)
    name = re.sub(r"\s+", "_", name).strip("._-")
    return (name or "note")[:80]


def unique_path(directory: Path, stem: str, suffix: str) -> Path:
    candidate = directory / f"{stem}{suffix}"
    if not candidate.exists():
        return candidate
    for number in range(1, 10000):
        candidate = directory / f"{stem}-{number}{suffix}"
        if not candidate.exists():
            return candidate
    raise RuntimeError("Не удалось подобрать имя файла")


def parse_notes(output: str) -> list[dict]:
    notes = []
    for block in output.split("@@NOTE@@"):
        block = block.strip("\n")
        if not block:
            continue
        title = "Без названия"
        modified = ""
        body = block
        lines = block.splitlines()
        if lines and lines[0].startswith("TITLE:"):
            title = lines[0][len("TITLE:"):].strip() or title
            lines = lines[1:]
        if lines and lines[0].startswith("MODIFIED:"):
            modified = lines[0][len("MODIFIED:"):].strip()
            lines = lines[1:]
        body = "\n".join(lines)
        if body.startswith("BODY:"):
            body = body[len("BODY:"):].lstrip("\n")
        notes.append({"title": title, "modified": modified, "body": body})
    return notes


def main() -> int:
    parser = argparse.ArgumentParser(description="Экспорт заметок Apple Notes")
    parser.add_argument("--output", type=Path, default=Path("notes-export"))
    parser.add_argument("--format", choices=("html", "txt"), default="html")
    parser.add_argument("--force", action="store_true", help="Перезаписывать совпадающие имена")
    args = parser.parse_args()

    result = subprocess.run(
        ["osascript", "-e", APPLESCRIPT],
        capture_output=True,
        text=True,
        check=False,
    )
    if result.returncode != 0:
        print("Не удалось прочитать заметки.", file=sys.stderr)
        print(result.stderr.strip(), file=sys.stderr)
        return 2

    notes = parse_notes(result.stdout)
    output_dir = args.output.expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    suffix = ".html" if args.format == "html" else ".txt"
    saved = 0

    for note in notes:
        stem = safe_name(note["title"])
        path = output_dir / f"{stem}{suffix}"
        if path.exists() and not args.force:
            path = unique_path(output_dir, stem, suffix)
        if args.format == "html":
            content = (
                "<!doctype html>\n"
                "<meta charset=\"utf-8\">\n"
                f"<title>{html.escape(note['title'])}</title>\n"
                f"<!-- modified: {html.escape(note['modified'])} -->\n"
                f"<h1>{html.escape(note['title'])}</h1>\n"
                f"{note['body']}\n"
            )
        else:
            content = f"{note['title']}\n\n{strip_html(note['body'])}\n"
        path.write_text(content, encoding="utf-8")
        saved += 1
        print(f"Сохранено: {path}")

    print(f"Заметок: {len(notes)}. Файлов записано: {saved}. Каталог: {output_dir}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Скрипты работают с файлами и настройками системы. Перед запуском прочитайте код и проверьте пути. Особенно если скрипт удаляет, перезаписывает или перемещает данные.

CLI 1.0.0

Скачать без браузера

Команда скачает этот файл в текущую папку. CLI работает на Windows, macOS и Linux.

scriptdock get macos-notes-export
  • Поиск по всему каталогу
  • Python 3.10+
  • Без внешних пакетов
Скачать CLI

GUI-версия готовится. Подробнее

Категория

macOS

Shell, Python и автоматизация macOS без лишних приложений.