如何在 python 程序中保存信息?



更具体地说,我想编写一个简单的预算跟踪程序,我想知道如何告诉程序我今天花了多少钱以及花在什么地方,以便我可以在第二天打开程序与最后一天更改的预算?

如果程序不是很大,您可以使用文件并将数据存储在那里。 您在程序加载时加载数据,读取并执行计算,并在程序关闭时保存文件。

如果你的程序变得非常大,你可能想使用数据库。

  • 关于蟒蛇文件的教程
  • python 3.6 的官方文件文档
  • 数据库

您可以在需要时使用一个简单的文本文件,将记录附加到该文件。随着时间的推移,您始终可以将其转换为更精细的内容:

class Record:
archive = 'archive.txt'
def __init__(self, date, purpose, amount):
self.date = date
self.purpose = purpose
self.amount = amount
self.save_record()
def save_record(self):
with open('archive.txt', 'a') as f:
f.write(str(self))
def __str__(self):
return f'{self.date}, {self.purpose}, {self.amount}n'

if __name__ == '__main__':
Record('20180604', 'candy', 3.20)
Record('20180507', 'chocolate', 4.20)

您可以查找python提供的各种格式的时间戳,以及csv模块以获取有关如何改进此问题的想法。

一个简单的文件读取脚本将大大有助于检索记录。

您可以使用文本文件,如下所示:

def func():
action = input("Action: ")
if action == "save":
savedataL1 = input(">")
savedataL2 = input(">")
savedataL3 = input(">")
savedataL4 = input(">")
savedataL5 = input(">")
file = open("foo.txt","w+")
file.truncate()
file.write(str(banoffee.hexlify(bytes(savedataL1, 'utf8'))).replace("b'","").replace("'","") + "n")
file.write(str(banoffee.hexlify(bytes(savedataL2, 'utf8'))).replace("b'","").replace("'","") + "n")
file.write(str(banoffee.hexlify(bytes(savedataL3, 'utf8'))).replace("b'","").replace("'","") + "n")
file.write(str(banoffee.hexlify(bytes(savedataL4, 'utf8'))).replace("b'","").replace("'","") + "n")
file.write(str(banoffee.hexlify(bytes(savedataL5, 'utf8'))).replace("b'","").replace("'","") + "n")
elif action == "load":
file = open("foo.txt","r")
lines=file.readlines()
print("")
print(str(banoffee.unhexlify(bytearray(lines[0].strip(), 'utf8')))[2:-1])
print(str(banoffee.unhexlify(bytearray(lines[1].strip(), 'utf8')))[2:-1])
print(str(banoffee.unhexlify(bytearray(lines[2].strip(), 'utf8')))[2:-1])
print(str(banoffee.unhexlify(bytearray(lines[3].strip(), 'utf8')))[2:-1])
print(str(banoffee.unhexlify(bytearray(lines[4].strip(), 'utf8')))[2:-1])

else:
func()
func()

最新更新