Python实现简单的记账本功能
目标:
1.使用序列化cPickle
2.账户中钱要大于花费的钱,否则提示请存钱
2.编写函数,实现存钱,花钱,查询及退出功能
1.序列化
pickle是python实现序列化的模块,次模块存在使用C语言编写模块,用法相同,但执行效率更高,所以优先使用C模块编写的序列化模块cPickle。
2.编写函数,实现存钱,花钱,查询及退出功能
代码如下:
[root@localhost 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) + amountwith 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) - amountif 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."continueif choice in '01':amount = int(raw_input("Amount: "))comment = raw_input("Comment: ")args = (w_file, r_file, amount, comment)if choice == '3':breakcmds[choice](*args)if __name__ == '__main__':print show_menu()
•运行代码,测试效果
[root@localhost 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:utf8import os,sys import time ''' 1.运行该脚本会生成一个balance.txt文件,并设置初始账户余额:¥10000 2.运行该脚本会生成一个account.txt文件,并记录账户消费信息详情。 '''def save():date = time.strftime("%Y-%m-%d")cost = 0while 1:try:save = int(raw_input("请输入存款金额: ").strip())except ValueError:print "\033[31m请输入数值类型,重新输入!\033[0m"continueexcept (KeyboardInterrupt,EOFError):sys.exit("\n\033[31m程序退出\033[0m")if save <= 0:print "\033[31m请输入一个大于0的存款金额:\033[0m"continuewhile 1:try:comment = str(raw_input("请输入存款信息: "))except (KeyboardInterrupt,EOFError):sys.exit("\n\033[31m程序退出\033[0m")if not comment:continuebreakbreakbalance = 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 = 0date = time.strftime("%Y-%m-%d")while 1:try:cost = int(raw_input("请输入消费金额: ").strip())except ValueError:print "\033[31m请输入数值类型,重新输入!!!\033[0m"continueexcept (KeyboardInterrupt,EOFError):sys.exit("\n\033[31m程序退出\033[0m")if cost <= 0:print "\033[31m请输入一个大于0的消费金额:\033[0m"continuebreakbalance = rekcon_balance(save,cost)while balance == -1:print "\033[31m余额不足,请充值或进行其他操作!!!\033[0m"breakelse:while 1:try:comment = str(raw_input("请输入消费信息: "))except (KeyboardInterrupt,EOFError):sys.exit("\n\033[31m程序退出\033[0m")if not comment:continuebreaka.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 = 10000balance += saveif cost > balance:balance = -1return balancebalance -= cost# with open('balance.txt', 'w') as f:# balance = str(balance)# f.write(balance)return balancedef balance():try:with open('balance.txt', 'r') as b:balance = b.readline()except IOError,e:balance = 10000print "\033[31m初始账户余额:\033[0m¥%s" % balanceelse:print "\033[31m当前账户余额:\033[0m¥%s" % balancedef 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"continueif choice not in '01234':print "\033[31m无效输入,请重新输入!!!\033[0m"continueif choice == 4:breakcmds[choice]()if __name__ == '__main__':a = open('account.txt','a')print show_menu()a.close()
转载于:https://www.cnblogs.com/xkops/p/6257026.html
Python实现简单的记账本功能相关推荐
- 【Python 第1篇】如何用Python实现简单的文字输出功能
相比于C++,Python的文字输出功能可谓相当简单,只需一行代码即可输出所需的文字,下面就来和我一起学习吧! 例如,想输出"hello world",就在界面输入如下的代码: p ...
- 使用python实现简单的单机对讲机功能
一.创建服务端 要实现单机的对讲机功能,就需要使用到socket(套接字)相关内容.常用的TCP/IP协议共有3种套接字类型,这里只需要使用最简单的流式套接字(SOCK_STREAM). 首先,导入p ...
- 用python做一个购物车编程_利用python实现简单的循环购物车功能示例代码
本文主要给大家介绍了关于python实现循环购物车功能的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 示例代码 # -*- coding: utf-8 -*- __author__ = ...
- python简单读写记账代码_Python之区块链简单记账本实现
个人博客:http://101python.cn/ 在上一篇<>中讲述了区块链的基础知识,并用Python实现了区块和区块链的结构.在本篇中,将基于上面的内容实现一个简单的记账本功能. 记 ...
- python抢茅台_python实现简单淘宝秒杀功能
本文实例为大家分享了Python淘宝秒杀的具体代码,供大家参考,具体内容如下 昨天茅台在线上搞秒杀,本来想着靠我惊人的手速去秒一瓶,结果.... 所以痛定思痛,想想还是用脚本更靠谱.就在网上搜啊搜,看 ...
- python手机端秒杀_python实现简单淘宝秒杀功能
这篇文章主要为大家详细介绍了python实现简单淘宝秒杀功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 本文实例为大家分享了Python淘宝秒杀的具体代码,供大家参考,具体内容如下 昨天茅台在 ...
- Python django实现简单的邮件系统发送邮件功能
Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: ...
- python读取json配置文件_Python简单读取json文件功能示例
本文实例讲述了Python简单读取json文件功能.分享给大家供大家参考,具体如下: read_json.json: { "rule":{ "namespace" ...
- python服务端语言_使用Python实现简单的服务器功能
socket接口是实际上是操作系统提供的系统调用.socket的使用并不局限于Python语言,你可以用C或者Java来写出同样的socket服务器,而所有语言使用socket的方式都类似(Apach ...
最新文章
- 2021年2月程序员工资统计,又拖后腿了……
- Bzoj2141: 排队
- win10安装oracle 11g最新亲身经历操作记录
- Docker系列之二:基于容器的自动构建
- MediaWiki/升级
- angular2创建应用_如何使用Angular和SQLite3创建Electron应用程序。
- 666! 玩王者,识英雄,这样也能上顶会!
- nginx 启动命令_Nginx实战001:Window中配置使用Nginx入门
- 国家级精品课程计算机程序设计,国家级精品课程
- 震惊!99%的网络工程师都不知道的组播问题
- kuberneters集群中使用traefik发布服务
- 计算机技术应用于测量,在测量绘图中计算机技术应用探析.doc
- 干货|读完这篇,再也不担心基金从业考试!
- IOS音视频(二)AVFoundation视频捕捉
- Local time zone must be set-see zic manual page
- 为虚拟机配置静态ip地址
- 金蝶虚拟化客户端连不上服务器,金蝶kis客户端远程连接服务器
- 2020.9.2丨遗传图谱产品类型
- Python与GIS
- FastAPI(55)- Events: startup - shutdown 启动/关闭事件