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

2024-06-07 06:17:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找有关如何使用python读取GnuCash文件的信息。我已经阅读过这个^{},它为GnuCash库提供了Python绑定,但是目前需要做很多工作(例如依赖项、头等)。这些指令是为Linux环境和相当旧的GnuCash版本(2.0.x)量身定制的。我正在运行GnuCash 2.2.9。虽然我可以操作Linux命令行,但我在Windows XP上运行GnuCash。

我的主要目标是读取GnuCash文件,这样我就可以使用matplotlibwxpython创建自己的可视化动态报表。我还没心情学这个计划。

我希望有人能给我一个好的开始。据我对GnuCash和Python的了解,我认为可能有人知道以下类型的解决方案:

  1. 除了this one from the GnuCash wiki之外,最近更新的文档
  2. 一些解决方法,比如导出到某种文件格式,对于这种格式,有一个更成熟的Python库可以读取它。

除了上面提到的,你们可能还有更好的建议。


Tags: 文件命令行版本信息目标环境matplotliblinux
3条回答

GNUCash 2.4出局了。

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

支持Sqlite、MySQL和PostgreSQL(真酷!)

我发布了piecash,它是SQL保存的GnuCash书籍的python接口,使用SQLAlchemy作为基础(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)

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

# 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)

最新版本还允许将拆分信息直接提取到pandas数据帧,以便使用

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"]])

你在说数据文件吗?从那里wiki,看起来它们只是压缩的XML文件。使用Python,您可以使用gzip module解压缩它们,然后使用available XML parsers解析它们。

元素树示例

>>> 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'

相关问题 更多 >