from time import strftime
import color #输出颜色的模块
import pickle
import os
#记录收入
def save(fname):
now_time = strftime('%Y-%m-%d') # 当前时间
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
old_balance = int(records[-1][-2]) # 上一次余额
try:
money = int(input('收入(元): '))
content = input('收入说明: ')
except ValueError as e:
print('\033[31m输入错误:\033[0m', e)
else:
all_balance = old_balance + money #收入后的总余额
new_bill = [now_time, money, 0, all_balance, content] #新的账单
records.append(new_bill)
with open(fname,'wb') as fobj:
pickle.dump(records, fobj)
# save_bill(records)
# print(bill)
color.cecho(34, '操作成功')
#记录支出
def cost(fname):
now_time = strftime('%Y-%m-%d') # 当前时间
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
old_balance = int(records[-1][-2]) # 上一次余额
try:
money = int(input('支出(元): '))
content = input('支出说明: ')
except ValueError as e:
print('\033[31m输入错误:\033[0m', e)
else:
all_balance = old_balance - money # 收入后的总余额
new_bill = [now_time, 0, money, all_balance, content] # 新的账单
records.append(new_bill)
with open(fname, 'wb') as fobj:
pickle.dump(records, fobj)
# save_bill(records)
# print(bill)
color.cecho(34, '操作成功')
#查看账单
def query(fname):
#打印表头
print('%-12s%-8s%-8s%-12s%-15s' % ('date', 'save', 'cost', 'balance', 'comment'))
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
for i in records:
print('%-12s%-8s%-8s%-12s%-15s' % tuple(i))
#功能程序
def show_menu():
cmds = {'0':save, '1':cost, '2':query}
prompt = '''(0)收入
(1)支出
(2)查看
(3)退出
输入(0/1/2/3):'''
# 初始化账单
bill = [['2019-07-07', 0, 0, 10000, 'init']]
fname = '/tmp/record.data' # 存储账单的文件
if not os.path.exists(fname):
with open(fname, 'wb') as f:
pickle.dump(bill, f)
while True:
choice = input(prompt).strip()
if choice not in '0123':
print('输入错误,请重试')
continue
if choice == '3':
color.cecho(36, '生不带来,死不带去,该花就花')
break
cmds[choice](fname)
print('-' * 40)
#####################################主程序#####################################
if __name__ == '__main__':
try:
show_menu()
except (ValueError, KeyboardInterrupt, EOFError,FileNotFoundError) as e:
print('\033[31m输入有误:\033[0m', e)