基于Python的模拟记账功能

import os
import pickle
from time import strftime
# 入账
def save(fname):
    amount = int(input('金额:'))
    comment = input('备注:')
    date = strftime('%Y-%m-%d')
    # 从文件中取出全部记录
    with open(fname,'rb') as fobj:
        recods = pickle.load(fobj)
    # 计算最新余额
    balance = recods[-1][-2] + amount
    recod = [date,amount,0,balance,comment]
    recods.append(recod)
    # 将更新后的数据重新写入文件
    with open(fname,'wb')as fobj:
        pickle.dump(recods,fobj)
# 开销
def cost(fname):
    amount = int(input('金额:'))
    comment = input('备注:')
    date = strftime('%Y-%m-%d')
    # 从文件中取出全部记录
    with open(fname, 'rb') as fobj:
        recods = pickle.load(fobj)
    # 计算最新余额
    balance = recods[-1][-2] - amount
    recod = [date, 0, amount, balance, comment]
    recods.append(recod)
    # 将更新后的数据重新写入文件
    with open(fname, 'wb')as fobj:
        pickle.dump(recods, fobj)
#查询
def query(fname):
    with open(fname,'rb') as fobj:
        recods = pickle.load(fobj)
    print('%-11s%-8s%-8s%-12s%-20s' % ('时间','入账','开销','余额','备注'))
    for i in tuple(recods):
        print('%-12s%-10s%-10s%-12s%-20s'% tuple(i))
# 显示
def show_menu():
    prompt = ''' 0 入账
1 开销
2 查询
3 退出
请选择(0/1/2/3):'''
    cmds = {'0': save,'1': cost,'2': query}
    fname = 'account.data'
    init_data = [
        [strftime('%Y-%m-%d') , 0, 0, 10000, 'init data']
    ]
    # 如果文件不存在,把初始化数据写进去
    if not os.path.exists(fname):
        with open(fname,'wb') as fobj:
            pickle.dump(init_data,fobj)

    while True:
        choice = input(prompt).strip()
        if choice not in ['0','1','2','3']:
            print('无效输入')
            continue
        if choice == '3':
            print('\nBye~~')
            break
        cmds[choice](fname)

if __name__ == '__main__':
    show_menu()

你可能感兴趣的:(基于Python的模拟记账功能)