Python实现简单的记账本功能

目标:

  1.使用序列化cPickle

  2.账户中钱要大于花费的钱,否则提示请存钱

  2.编写函数,实现存钱,花钱,查询及退出功能

1.序列化

  pickle是python实现序列化的模块,次模块存在使用C语言编写模块,用法相同,但执行效率更高,所以优先使用C模块编写的序列化模块cPickle。

2.编写函数,实现存钱,花钱,查询及退出功能

代码如下:

[[email protected] python]# cat new_account.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os,time
import cPickle as p
def save_money(wallet, record, amount, comment):
    date = time.strftime("%Y-%m-%d")

    with open(wallet) as fobj:
        balance = p.load(fobj) + amount

    with open(wallet, ‘wb‘) as fobj:
        p.dump(balance, fobj)

    with open(record, ‘a‘) as fobj:
        fobj.write(
            "%-12s%-8s%-8s%-10s%-20s\n" % (
                date,  ‘N/A‘, amount, balance, comment
            )
        )

def cost_money(wallet, record, amount, comment):
    date = time.strftime("%Y-%m-%d")

    with open(wallet) as fobj:
        balance = p.load(fobj) - amount
    if balance < 0:
        print "余额不足,请先存钱或进行其他操作!"
    else:
        with open(wallet, ‘wb‘) as fobj:
            p.dump(balance, fobj)

        with open(record, ‘a‘) as fobj:
            fobj.write(
                "%-12s%-8s%-8s%-10s%-20s\n" % (
                    date, amount, ‘N/A‘, balance, comment
                )
            )

def query_money(wallet, record):
    print "%-12s%-8s%-8s%-10s%-20s" % (
            ‘date‘, ‘cost‘, ‘save‘, ‘balance‘, ‘comment‘
        )
    with open(record) as fobj:
        for line in fobj:
            print line,
    with open(wallet) as fobj:
        print "New Balance:\n%s" % p.load(fobj)

def show_menu():
    w_file = ‘wallet.data‘
    r_file = ‘record.txt‘
    cmds = {
        ‘0‘: save_money,
        ‘1‘: cost_money,
        ‘2‘: query_money
    }
    prompt = """(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): """
    if not os.path.isfile(w_file):
        with open(w_file, ‘w‘) as fobj:
            p.dump(0, fobj)
    if not os.path.isfile(r_file):
        os.mknod(r_file)

    while True:
        args = (w_file, r_file)
        choice = raw_input(prompt).strip()[0]
        if choice not in ‘0123‘:
            print "Invalid input, Try again."
            continue

        if choice in ‘01‘:
            amount = int(raw_input("Amount: "))
            comment = raw_input("Comment: ")
            args = (w_file, r_file, amount, comment)

        if choice == ‘3‘:
            break

        cmds[choice](*args)

if __name__ == ‘__main__‘:
    print show_menu()

?运行代码,测试效果

[[email protected] python]# python new_account.py
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 2
date        cost    save    balance   comment
New Balance:
0
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 1
Amount: 100
Comment: cost 100
余额不足,请先存钱或进行其他操作!
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 0
Amount: 100
Comment: save 100
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 2
date        cost    save    balance   comment
2017-01-06  N/A     100     100       save 100
New Balance:
100
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 1
Amount: 101
Comment: cost 101
余额不足,请先存钱或进行其他操作!
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 1
Amount: 100
Comment: cost 100
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3): 2
date        cost    save    balance   comment
2017-01-06  N/A     100     100       save 100
2017-01-06  100     N/A     0         cost 100
New Balance:
0
(0) save money
(1) spend money
(2) query detail
(3) quit
Please input your choice(0/1/2/3):

*附录

1.如下是自己初次编写的代码,函数不具备通用性功能。

#!/usr/bin/env python
#coding:utf8

import os,sys
import time
‘‘‘
1.运行该脚本会生成一个balance.txt文件,并设置初始账户余额:¥10000
2.运行该脚本会生成一个account.txt文件,并记录账户消费信息详情。
‘‘‘

def save():
    date = time.strftime("%Y-%m-%d")
    cost = 0

    while 1:
        try:
            save = int(raw_input("请输入存款金额: ").strip())
        except ValueError:
            print "\033[31m请输入数值类型,重新输入!\033[0m"
            continue
        except (KeyboardInterrupt,EOFError):
            sys.exit("\n\033[31m程序退出\033[0m")

        if save <= 0:
            print "\033[31m请输入一个大于0的存款金额:\033[0m"
            continue

        while 1:
            try:
                comment = str(raw_input("请输入存款信息: "))
            except (KeyboardInterrupt,EOFError):
                sys.exit("\n\033[31m程序退出\033[0m")
            if not comment:
                continue
            break
        break
    balance = rekcon_balance(save,cost)
    a.write(‘%-12s%-12s%-12s%-12s%-12s\n‘ %(date, cost, save, balance, comment))
    a.flush()
    with open(‘balance.txt‘, ‘w‘) as b:
        balance = str(balance)
        b.write(balance)

def cost():
    save = 0
    date = time.strftime("%Y-%m-%d")
    while 1:
        try:
            cost = int(raw_input("请输入消费金额: ").strip())
        except ValueError:
            print "\033[31m请输入数值类型,重新输入!!!\033[0m"
            continue
        except (KeyboardInterrupt,EOFError):
            sys.exit("\n\033[31m程序退出\033[0m")

        if cost <= 0:
            print "\033[31m请输入一个大于0的消费金额:\033[0m"
            continue
        break

    balance = rekcon_balance(save,cost)
    while balance == -1:
        print "\033[31m余额不足,请充值或进行其他操作!!!\033[0m"
        break
    else:
        while 1:
            try:
                comment = str(raw_input("请输入消费信息: "))
            except (KeyboardInterrupt,EOFError):
                sys.exit("\n\033[31m程序退出\033[0m")
            if not comment:
                continue
            break
        a.write(‘%-12s%-12s%-12s%-12s%-12s\n‘ %(date, cost, save, balance, comment))
        with open(‘balance.txt‘, ‘w‘) as b:
            balance = str(balance)
            b.write(balance)
    a.flush()

def rekcon_balance(save,cost):
    try:
        with open(‘balance.txt‘, ‘r‘) as b:
            balance = b.readline()
            balance = int(balance)
    except IOError:
        balance = 10000

    balance += save
    if cost > balance:
        balance = -1
        return balance

    balance -= cost

    # with open(‘balance.txt‘, ‘w‘) as f:
    #     balance = str(balance)
    #     f.write(balance)
    return balance

def balance():
    try:
        with open(‘balance.txt‘, ‘r‘) as b:
            balance = b.readline()
    except IOError,e:
        balance = 10000
        print "\033[31m初始账户余额:\033[0m¥%s" % balance
    else:
        print "\033[31m当前账户余额:\033[0m¥%s" % balance

def view():
    print ‘账户金额详细信息‘.center(78,‘*‘)
    print "%-12s%-12s%-12s%-12s%-12s\n" %(‘Date‘, ‘Cost‘, ‘Save‘, ‘Balance‘, ‘Comment‘),
    with open(‘account.txt‘,‘r‘) as b:
        for line in b.readlines():
            print line,
    print ‘*‘.center(70,‘*‘)
def show_menu():
    cmds = {
    ‘0‘: save, ‘1‘: cost, ‘2‘: balance, ‘3‘: view, ‘4‘: quit
    }
    prompt = """\033[32m-----------------------------
(0): save money
(1): cost money
(2): balance
(3): view detail
(4): quit
-----------------------------\033[0m
Please Input Your Choice: """
    while 1:
        try:
            choice = raw_input(prompt).strip()[0]
        except (KeyboardInterrupt,EOFError):
            sys.exit("\n\033[31m程序退出\033[0m")
        except IndexError:
            print "\033[31m无效输入,请重新输入!!!\033[0m"
            continue

        if choice not in ‘01234‘:
            print "\033[31m无效输入,请重新输入!!!\033[0m"
            continue

        if choice == 4:
            break

        cmds[choice]()

if __name__ == ‘__main__‘:
    a = open(‘account.txt‘,‘a‘)
    print show_menu()
    a.close()
时间: 2025-01-01 09:13:27

Python实现简单的记账本功能的相关文章

python实现简单的循环购物车小功能

python实现简单的循环购物车小功能 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s", 5000), ("book python", 81), ("iwach", 3200), ("电视机", 2200) ] def zero(name): if len(name) == 0: print("\033[31;1m您的输

完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能

#!/bin/usr/env python#coding=utf-8'''完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能'''try: a=int(raw_input("please input a number:"))except ValueError: print("第一个运算数字输入非数字") try: b=int(raw_input("please input another number:"))except Val

Python django实现简单的邮件系统发送邮件功能

Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: 1.首先这份文档看三两遍是不行的,很多东西再看一遍就通顺了.2.send_mail().send_mass_mail()都是对EmailMessage类使用方式的一个轻度封装,所以要关注底层的EmailMessage.3.异常处理防止邮件头注入.4.一定要弄懂Email backends 邮件发送后

python编写简单的html登陆页面(2)

1  在python编写简单的html登陆页面(1)的基础上在延伸一下: 可以将动态分配数据,实现页面跳转功能: 2  跳转到新的页面:return render_template('home1.html') 3  后台代码如下 4  前端html:

python超简单的web服务器

今天无意google时看见,心里突然想说,python做web服务器,用不用这么简单啊,看来是我大惊小怪了. web1.py 1 2 3 #!/usr/bin/python import SimpleHTTPServer SimpleHTTPServer.test() web2.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #!/usr/bin/python import SimpleHTTPServer import SocketServer

Python的简单介绍/解释器/变量/变量的数据类型/用户交互及流程控制(if)

一.Python的简单介绍 1.python是一门 解释型弱类型编程语言. 2.特点: 简单.明确.优雅 二.python的解释器有哪些 CPython -- 官方提供的.,内部使用c语言来实现 IPython -- IPython是基于CPython之上的一个交互式解释器,也就是说,IPython只是在交互方式上有所增强,但是执行Python代码的功能和CPython是完全一样的.好多很多国产浏览器虽然外观不同,但内核其实都是调用了IE PyPy -- PyPy是另一个Python解释器,它的

Python 实现简单的登录注册界面

Python 实现简单的登录注册界面 注意:编写代码之前需要导入很重要的包 import tkinter as tk import pickle from tkinter import messagebox 主要实现的功能 首先在python字典里定义一对值{'admin':'admin'}如果登录成功显示"How are you! admin". 如果字典里没有一一对应的一对值{'Username':'Password'},则需要注册,紧接着再登录. 实现过程 登录界面 首先初始化一

觉得 Python 太“简单了”,这些题你能答对几个?

前言 觉得 Python 太"简单了"?作为一个 Python 开发者,我必须要给你一点人生经验,不然你不知道天高地厚!)一份满分 100 分的题,这篇文章就是记录下做这套题所踩过的坑. 下面的代码会报错,为什么? class A(object): x = 1 gen = (x for _ in xrange(10)) # gen=(x for _ in range(10)) if __name__ == "__main__": print(list(A.gen))

python中简单文件的输入三种方式

最近在自学python,简单的总结了一下文件的输入的方式. 1. f=open("foo.txt") line=f.readline() while line: print(line,end='') line=f.readline() f.close() 2. for line in open("foo.txt"): print(line,end='') 3. f=open("foo.txt") lines=f.readlines() for l