Reading and writing Org files¶
org_parser
¶
org_parser — Python bindings for the tree-sitter org-mode parser.
This package provides convenience helpers for loading and dumping Org Mode documents as org_parser.document.Document instances.
Functions:
| Name | Description |
|---|---|
load |
Load an Org Mode document from a file. |
loads |
Load an Org Mode document from a string. |
dump |
Write a parsed document to disk. |
dumps |
Return Org Mode text for a parsed document. |
load
¶
load(filename: str) -> Document
Load an Org Mode document from a file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
Path to the Org Mode file. |
required |
Returns:
| Type | Description |
|---|---|
Document
|
Parsed org_parser.document.Document instance. |
Example:
>>> from org_parser import load
>>> document = load('path/to/file.org')
>>> document.children[0].title_text
'Some heading'
loads
¶
loads(source: str, filename: str | None = None) -> Document
Load an Org Mode document from a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str
|
Org Mode text to parse. |
required |
filename
|
str | None
|
Optional filename to assign to the parsed document. |
None
|
Returns:
| Type | Description |
|---|---|
Document
|
Parsed org_parser.document.Document instance. |
Example:
>>> from org_parser import loads
>>> document = loads("* TODO Heading 1")
>>> document.children[0].todo
'TODO'
dump
¶
dump(
document: Document, filename: str | None = None
) -> None
Write a parsed document to disk.
The output path is filename when provided; otherwise document.filename.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Document
|
Parsed document instance. |
required |
filename
|
str | None
|
Optional output path. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither filename nor |
Example:
>>> from pathlib import Path
>>> from org_parser import dump, loads
>>> document = loads("* TODO Heading 1")
>>> dump(document, 'path/to/file.org')
>>> out = Path('path/to/file.org')
>>> out.read_text().startswith("* TODO")
True
dumps
¶
dumps(document: Document) -> str
Return Org Mode text for a parsed document.
Produces the complete document text including all headings. For clean (unmodified) parse-backed documents the original source is returned verbatim; for dirty documents every section is reconstructed from its semantic fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
document
|
Document
|
Parsed document instance. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Full Org Mode source text. |
Example:
>>> from org_parser import dumps, loads
>>> document = loads("* TODO Heading 1")
>>> dumps(document).startswith("* TODO")
True