[GNC] Access the Company Name in python

Raymond Smith raymondbarrettsmith at gmail.com
Sun Feb 16 19:06:50 EST 2020


I don't know if this is a good/robust solution, but I have been playing
with parsing gnucash xml files with python recently. This is how I would do
it.

This assumes a file in the same directory named 'test_business.gnucash'
that is saved with compression. If you save without compression, you can
make the following two edits, and it should work:
* gzip.open(fname) --> open(fname)
* filestr = StringIO(fi.read().decode('utf-8')) --> filestr =
StringIO(fi.read())


Contents of some script.py file:

from io import StringIO
import gzip
import os.path as osp
import xml.etree.ElementTree as ET

selfdir = osp.dirname(osp.realpath(__file__))

def main():
    fname = osp.join(selfdir, 'test_business.gnucash')
    with gzip.open(fname) as fi:
        # stackoverflow.com/questions/
        # 14853243/parsing-xml-with-namespace-in-python-via-elementtree
        # 17615414/how-to-convert-binary-string-to-normal-string-in-python3
        filestr = StringIO(fi.read().decode('utf-8'))
        ns = dict([node for _, node in ET.iterparse(filestr,
events=['start-ns'])])
        fi.seek(0)
        tree = ET.parse(fi)
    book = tree.getroot().find('gnc:book', ns)
    opt_slot = [slot for slot in book.find('book:slots',
ns).findall('slot', ns)
                if slot.find('slot:key', ns).text == 'options'][0]
    bus_slot = [slot for slot in opt_slot.find('slot:value',
ns).findall('slot', ns)
               if slot.find('slot:key', ns).text == 'Business'][0]
    busname_slot = [slot for slot in bus_slot.find('slot:value',
ns).findall('slot', ns)
                   if slot.find('slot:key', ns).text == 'Company Name'][0]
    busname = busname_slot.find('slot:value', ns).text
    print(busname)


if __name__ == '__main__':
    main()

On Thu, Jan 30, 2020 at 1:42 PM <gcash at nailedtotheperch.com> wrote:

> What is the most straight forward way to access (read) the company name
> in python. I can see it the XML, but that seems a little fragile. I'm
> talking about the company name entered in File->Properties->Book
> Option->Business not a Vendor or Customer Name.
>
> Could somebody give me a quick pointer to the module and method.
>
>
> Thanks
>
>
>
>
> _______________________________________________
> gnucash-user mailing list
> gnucash-user at gnucash.org
> To update your subscription preferences or to unsubscribe:
> https://lists.gnucash.org/mailman/listinfo/gnucash-user
> If you are using Nabble or Gmane, please see
> https://wiki.gnucash.org/wiki/Mailing_Lists for more information.
> -----
> Please remember to CC this list on all your replies.
> You can do this by using Reply-To-List or Reply-All.
>


More information about the gnucash-user mailing list