Tutorial : using existing objects¶
Opening an existing Book¶
To open an existing GnuCash document (and get the related Book
), use the open_book()
function:
import piecash
# for a sqlite3 document
book = piecash.open_book("existing_file.gnucash")
# or through an URI connection string for sqlite3
book = piecash.open_book(uri_conn="sqlite:///existing_file.gnucash")
# or for postgres
book = piecash.open_book(uri_conn="postgres://user:passwd@localhost/existing_gnucash_db")
The documents are open as readonly per default. To allow RW access, specify explicitly readonly=False as:
book = piecash.open_book("existing_file.gnucash", readonly=False)
When opening in full access (readonly=False), piecash will automatically create a backup file named filename.piecash_YYYYMMDD_HHMMSS with the original file. To avoid creating the backup file, specificy backup=False as:
book = piecash.open_book("existing_file.gnucash", readonly=False, backup=False)
To force opening the file even through there is a lock on it, use the open_if_lock=True argument:
book = piecash.open_book("existing_file.gnucash", open_if_lock=True)
Access to objects¶
Once a GnuCash book is opened through a piecash.core.book.Book
, GnuCash objects can be accessed
through two different patterns:
The object model
In this mode, we access elements through their natural relations, starting from the book and jumping from one object to the other:
In [1]: book = open_book(gnucash_books + "default_book.gnucash") In [2]: book.root_account # accessing the root_account Out[2]: Account<[EUR]> In [3]: # looping through the children accounts of the root_account ...: for acc in book.root_account.children: ...: print(acc) ...: