如何从另一个python文件更新python文件中的数据?

2024-09-30 16:19:28 发布

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

我正在尝试创建简单的“accounter”,它可以显示您的现金余额和运营日志。操作很简单:接收(金额,主题)和支出(金额,主题)。它们更改平衡并将更改写入带有时间戳的日志中。应该是的

我正在尝试使用另一个.py文件作为数据库。虽然我可以导入、读取和使用数据库,但似乎找不到将更改写入数据库的方法。在任何地方都找不到我需要的解决方案。有一些方法,比如使用json和其他。但我正试图使用py文件

下面是db.py:

balance = 0

balance_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>方法,这将是一件好事


Tags: 文件方法py数据库主题db时间金额
1条回答
网友
1楼 · 发布于 2024-09-30 16:19:28

如果我理解我的意思,我相信用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)

相关问题 更多 >