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

时间:2018-06-04 08:38:50

标签: python

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

3 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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

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模块,了解如何改进这一点。

一个简单的文件读取脚本,可以很长的路径来检索记录。

答案 2 :(得分:0)

您可以使用文本文件,类似于:

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()
相关问题