我正在尝试创建简单的“帐户”,它可以显示您的现金余额和操作日志。操作很简单:receive(amount, subject) 和 spend(amount, subject)。他们更改余额并将更改写入带有时间戳的日志中。应该。我正在尝试使用另一个 .py 文件作为数据库。虽然我可以导入、读取和使用数据库,但我似乎找不到将更改写入其中的方法。在任何地方都找不到我需要的任何解决方案。有一些方法,比如使用 json 等。但我正在尝试完全使用 py 文件。这是 db.py:balance = 0balance_logs = [ ['305', 'spent','5','coke','2020-08-18 20:00'], ['202', 'spent','3','icecream','2020-08-18 20:00']]所以,我需要更改balance值并将列表附加到balance_logs. 另外我可能会在 db.py 中添加更多数据,所以如果我不需要<copy file contents fully -> modify the parts you need -> dump into file, by fully recreating it>方法就好了。
1 回答

九州编程
TA贡献1785条经验 获得超4个赞
如果我明白我的意思,我相信以 json 格式保存这个文件就可以了。我将尝试在此处总结基础知识。要从 json 打开并正确加载数据,您可以使用:
import json
with open('example.txt') as json_file:
data = json.load(json_file)
要将数据保存到文件,您可以使用:
import json
with open('example.txt', 'w') as json_file:
json.dump(data, json_file)
要用json追加数据,可以混合使用这两者,比如把json中存储的字典的一部分取出来,对它进行操作,然后再次保存。一个例子是:
import json
with open('example.txt') as json_file:
data = json.load(json_file)
# Do something to the data, for example...
data['foo'] = 'bar'
with open('example.txt', 'w') as json_file:
json.dump(data, json_file)
添加回答
举报
0/150
提交
取消