#====================================#
#花销记账单#
#====================================#
#datetime:2020-1-9 9:20:00
#author: chenshuai
#email: csawyy@163.com
#解题思路
'调用模块-定义函数-循环判断-异常报错优化-退出'
--------------------------------------------------------------------------
#python脚本-交互式;注意格式
import os
import pickle
from timeimport strftime
def save(fname):
'用于记录收入'
try:
amount =int(input('输入金额:'))
comment =input('备注:')
except ValueError:
print('无效的金额!')
return
#函数return类似于循环的break,结束函数
except (KeyboardInterrupt,EOFError):
print('\n Bye-bye')
exit()
date = strftime('%Y-%m-%d')
#取出全部的收支情况列表
with open(fname,'rb')as fobj:
records = pickle.load(fobj)
#计算最新余额
balance = records[-1][-2] + amount
#构建收入情况列表
line = [date,amount,0,balance,comment]
records.append(line)
#将更新后的收支情况列表写回文件
with open(fname,'wb')as fobj:
pickle.dump(records,fobj)
def cost(fname):
'用于记录支出'
amount =int(input('输入金额:'))
comment =input('备注:')
date = strftime('%Y-%m-%d')
with open(fname,'rb')as fobj:
records = pickle.load(fobj)
balance = records[-1][-2] - amount
line = [date,0, amount,balance, comment]
records.append(line)
with open(fname,'wb')as fobj:
pickle.dump(records, fobj)
def query(fname):
#用于查询收支情况
with open(fname,'rb')as fobj:
records =pickle.load(fobj)
#打印内容
print('%-12s%-8s%-8s%-12s%-20s' % ('date','save','cost','balance','comment'))
for linein records:
print('%-12s%-8s%-8s%-12s%-20s'%tuple(line))
def show_menu():
cmds={'0':save,'1':cost,'2':query}
prompt="""
(0) 收入 (1) 支出 (2) 查询 (3) 退出
请选择(0/1/2/3):"""
# 定义变量:文件名称
fname ='account.data'
#初始化文件内容的格式(字段)
init_data=[['2020-01-09',0,0,10000,'init data']]
#文件不存在,则创建
if not os.path.exists(fname):
with open(fname,'wb')as fobj:
pickle.dump(init_data,fobj)
while 1:
try:
choice =input(prompt).strip()
except (KeyboardInterrupt,EOFError):
choice ='3'
if choicenot in ['0','1','2','3']:
print('\033[32;1m无效的输入,请重试!\033[0m')
continue
if choice =='3':
print('\n Bye-bye')
break
cmds[choice](fname)
if __name__ =='__main__':
show_menu()