# 转自https://www.jianshu.com/c/00c61372c46a网址 #1,记账时手头有一万块钱 #2,可以记录花的钱,存的钱,以及收支明细 #wallet文件内存总的钱数,余额 #record文件内存的是明细 import pickle import os import time def cost(wallet,record): #记录花钱的函数 amount = int(input('amount: ')) #输入数字 comment = input('comment: ') #输入 date = time.strftime('%Y-%m-%d') with open(wallet,'rb') as fobj: #从文件取总值减去amount balance = pickle.load(fobj) - amount with open(wallet,'wb') as fobj: pickle.dump(balance,fobj) #将上面得到的值再写入文件内 with open(record,'a') as fobj: #向record对应文件内追加各种信息 fobj.write( '%-15s%-8s%-8s%-8s%-20s\n' % (date,'',amount,balance,comment) ) def save(wallet,record): #记录存钱的函数 amount = int(input('amount: ')) comment = input('comment: ') date = time.strftime('%Y-%m-%d') with open(wallet,'rb') as fobj: balance = pickle.load(fobj) + amount with open(wallet,'wb') as fobj: pickle.dump(balance,fobj) with open(record,'a') as fobj: fobj.write( '%-15s%-8s%-8s%-8s%-20s\n' % (date,amount,'',balance,comment) ) def query(wallet,record): #查询收支明细的函数 print('%-15s%-8s%-8s%-8s%-20s' % ('date','save','cost','balance','comment')) with open(record) as fobj: #输出明细 for line in fobj: print(line,end='') with open(wallet,'rb') as fobj: #输出余额 balance = pickle.load(fobj) print("Latest Balance: %d" % balance) def show_menu(): cmds = {'0':save,'1':cost,'2':query} prompt = """(0) save (1) cost (2) query (3) exit Please input your choice(0/1/2/3): """ wallet = '/tmp/1wallet.data' record = '/tmp/1record.txt' if not os.path.exists(wallet): with open(wallet,'wb') as fobj: #如果/tmp/wallet.data不存在,则创建并写入数据10000 pickle.dump(10000,fobj) while True: try: choice = input(prompt).strip()[0] #去除空格,选取第一个数字 except ImportError: continue except (KeyboardInterrupt,EOFError): print() choice == '3' if choice not in '0123': print('Invalid input. Try again.') continue if choice == '3': break cmds[choice](wallet,record) #根据cmds字典和choice选择运行上面定义的函数即查询,花钱,存钱 if __name__ == '__main__': show_menu()