Python和GnuCash:从GnuCash文件中提取数据

Kit*_*Kit 4 python api matplotlib

我正在寻找有关如何使用python读取GnuCash文件的信息.我已经读过这个python-gnucash提供Python绑定到GnuCash库的内容,但是目前它需要做很多工作(例如依赖项,头文件等).这些说明是针对Linux环境而定制的,而且是一个相当古老的GnuCash版本(2.0.x).我正在运行GnuCash 2.2.9.虽然我可以操作Linux命令行,但我在Windows XP上运行GnuCash.

我的主要目标是阅读(没有计划编写)我的GnuCash文件,以便我可以使用matplotlib和创建自己的可视化动态报告wxpython.我还没有心情去学习Scheme.

我希望有人能指出我这方面的良好开端.据我所知,GnuCash和Python,我想有人可能知道以下类型的解决方案:

  1. 最近更新的文档除了来自GnuCash wiki的文档
  2. 一些解决方法,例如导出到某种文件格式,其中有一个更成熟的Python库可以读取它.

除了提到的那些,你们可能会有更好的建议.

小智 5

GNUCash 2.4已经发布.

可以导出到SQL,因此它比解析XML要容易得多.

支持Sqlite,MySQL和PostgreSQL(这有多酷!)

  • 在 Ubuntu 中使用 sudo apt-get install libdbd-sqlite3 来获取 GnuCash 2.6 中的 mysql 功能。然后在 GnuCash 中打开您的书并选择“文件”->“另存为...”并选择“mysql”作为数据格式。 (2认同)

sde*_*ten 5

我发布了piecash,这是一个python接口,用于保存使用SQLAlchemy作为基础的SQL保存的GnuCash书籍(https://github.com/sdementen/piecash).

有了它,您可以轻松访问书中包含的所有信息.

例如,要迭代书中的所有帐户:

from piecash import open_book

# open a book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # iterate over all accounts of the book
    for account in mybook.accounts:
        print(account)
Run Code Online (Sandbox Code Playgroud)

或者迭代"资产"帐户中的所有拆分:

# open the book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # retrieve the account by its fullname
    asset = mybook.accounts(fullname="Asset")
    # iterate over all its splits
    for split in asset.splits:
        print(split)
Run Code Online (Sandbox Code Playgroud)

最新版本还允许将拆分信息直接提取到pandas DataFrames,以便于绘图/分析

from piecash import open_book

# open a book
with open_book("some_book.gnucash", open_if_lock=True) as mybook:
    # extract all split information to a pandas DataFrame
    df = mybook.splits_df()

    # print for account "Asset" some information on the splits
    print(df.loc[df["account.fullname"] == "Asset",
                 ["transaction.post_date", "value"]])
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 4

你是在谈论数据文件吗?从wiki来看,它们看起来只是压缩的 XML 文件。使用 Python,您可以使用gzip 模块解压缩它们,然后使用任何可用的 XML 解析器解析它们。

元素树示例

>>> import xml.etree.cElementTree as ET
>>> xmlStr = '''<?xml version="1.0" encoding="UTF-8" ?>
<painting>
<img src="madonna.jpg" alt='Foligno Madonna, by Raphael'/>
<caption>This is Raphael's "Foligno" Madonna, painted in
     <date>1511</date>?<date>1512</date>.
</caption>
</painting>
'''
>>> tree = ET.fromstring(xmlStr)  #use parse or iterparse to read direct from file path
>>> tree.getchildren()
[<Element 'img' at 0x115efc0>, <Element 'caption' at 0x1173090>]
>>> tree.getchildren()[1].text
'This is Raphael\'s "Foligno" Madonna, painted in\n    '
>>> tree.getchildren()[0].get('src')
'madonna.jpg'
Run Code Online (Sandbox Code Playgroud)