蟒蛇。如何在文本数据库中编辑数据?

时间:2011-11-25 15:19:42

标签: python database file text rewrite

我有一个小的数据库文本文件db.txt:

(peter)
    name = peter
    surname = asd
    year = 23
(tom)
    name = tom
    surname = zaq
    year = 22
    hobby = sport
(paul)
    name = paul
    surname = zxc
    hobby = music
    job = teacher

如何从例如汤姆获取所有数据部分?我想进入变量:

(tom)
    name = tom
    surname = zaq
    year = 22
    hobby = sport

然后我想改变数据:

replace("year = 22", "year = 23")

并获得:

(tom)
    name = tom
    surname = zaq
    year = 23
    hobby = sport

现在添加(作业)和删除(姓氏)数据:

(tom)
    name = tom
    year = 23
    hobby = sport
    job = taxi driver

最后将更改的部分重写为旧的db.txt文件:

(peter)
    name = peter
    surname = asd
    year = 23
(tom)
    name = tom
    year = 23
    hobby = sport
    job = taxi driver
(paul)
    name = paul
    surname = zxc
    hobby = music
    job = teacher

任何解决方案或提示如何做到这一点?非常感谢!

2 个答案:

答案 0 :(得分:2)

根据@aitchnyu的建议使用PyYAML并对原始格式进行一些修改,这是一项简单的任务:

import yaml

text = """
peter:
    name: peter
    surname: asd
    year: 23
tom:
    name: tom
    surname: zaq
    year: 22
    hobby: sport
paul:
    name: paul
    surname: zxc
    hobby: music
    job: teacher
"""

persons = yaml.load(text)
persons["tom"]["year"] = persons["tom"]["year"]*4   # Tom is older now
print yaml.dump(persons, default_flow_style=False)

结果:

paul:
  hobby: music
  job: teacher
  name: paul
  surname: zxc
peter:
  name: peter
  surname: asd
  year: 23
tom:
  hobby: sport
  name: tom
  surname: zaq
  year: 88

当然,您应该从文件(db.txt)中读取“text”并在完成后写入

答案 1 :(得分:0)

Sebastien评论的附录:使用内存 SQLite DB。 SQLite已经嵌入在Python中,所以它只需要设置几行。


此外,除非无法更改该格式,请考虑 YAML 作为文本。 Python可以在一个步骤中轻松地转换为YAML和Python对象(由python dicts,列表,字符串,实数等组成的对象)。

http://pyyaml.org/wiki/PyYAML


所以我的建议是YAML - > Python对象 - > SQLite DB又回来了。