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) + 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 = {
'': save_money,
'': cost_money,
'': 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 '':
print "Invalid input, Try again."
continue if choice in '':
amount = int(raw_input("Amount: "))
comment = raw_input("Comment: ")
args = (w_file, r_file, amount, comment) if choice == '':
break cmds[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: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 = {
'': save, '': cost, '': balance, '': view, '': 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 '':
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()
Python实现简单的记账本功能的更多相关文章
- 完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能
#!/bin/usr/env python#coding=utf-8'''完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能'''try: a=int(raw_input(" ...
- Selenium + PhantomJS + python 简单实现爬虫的功能
Selenium 一.简介 selenium是一个用于Web应用自动化程序测试的工具,测试直接运行在浏览器中,就像真正的用户在操作一样 selenium2支持通过驱动真实浏览器(FirfoxDrive ...
- python实现简单的循环购物车小功能
python实现简单的循环购物车小功能 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s&quo ...
- Python django实现简单的邮件系统发送邮件功能
Python django实现简单的邮件系统发送邮件功能 本文实例讲述了Python django实现简单的邮件系统发送邮件功能. django邮件系统 Django发送邮件官方中文文档 总结如下: ...
- python网络编程--socketserver 和 ftp功能简单说明
1. socketserver 我们之前写的tcp协议的socket是不是一次只能和一个客户端通信,如果用socketserver可以实现和多个客户端通信.它是在socket的基础上进行了一层封装,也 ...
- python超简单的web服务器
今天无意google时看见,心里突然想说,python做web服务器,用不用这么简单啊,看来是我大惊小怪了. web1.py 1 2 3 #!/usr/bin/python import Simp ...
- python操作三大主流数据库(6)python操作mysql⑥新闻管理后台功能的完善(增、ajax异步删除新闻、改、查)
python操作mysql⑥新闻管理后台功能的完善(增.删.改.查)安装表单验证D:\python\python_mysql_redis_mongodb\version02>pip instal ...
- python 的排名,已经python的简单介绍
我在今天看了一篇文章,是简书的全网程序猿写的,Java已经退出神坛,python稳居第一. python是由龟叔写的,它在英文的意思是蟒蛇. 根据编程语言流行指数排行榜2019年2月的榜单 据了解,目 ...
- python实现简单的负载均衡
提到分发请求,相信大多数人首先会想到Nginx,Nginx作为一种多功能服务器,不仅提供了反向代理隐藏主机ip的能力,还拥有简单的缓存加速功能.当然Nginx最强大的功能还是分发请求,不仅提供了哈希, ...
随机推荐
- 简单快捷好用的vim配置和终端配置推荐
vim 配置实用spf13-vim,安装方便简单快捷,极力推荐. 另外oh-my-zsh 终端配置很好,与之搭配使用效果更佳. 安装都很简单,一个脚本搞定, 都是在gitHub上开源的,自行搜索,这里 ...
- Word中一些问题解决
word图片不显示或显示不全怎么办? http://jingyan.baidu.com/article/0f5fb099c5cb7a6d8334ea06.html
- Git Push 避免用户名和密码方法
参考这里: http://www.cnblogs.com/ballwql/p/3462104.html 亲测第一种方法有效
- Android想服务器传图片,透过流的方式。还有读取服务器图片(文件),也通过流的方式。
/** * Created by Administrator on 2016/7/19. */ import android.util.Log; import com.gtercn.asPolice. ...
- Bestcoder Round #84
A题 Aaronson http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=718&pid=1001 感觉一 ...
- 桶装水 送水 消费充值PDA会员管理系统 介绍
桶装水 送水 消费充值PDA会员管理系统 介绍 主要功能:会员管理临时开卡.新增会员.修改会员.删除会员场馆管理仓管信息管理.租凭信息管理会员卡管理会员卡类型设置.会员发卡.会员信息管理.体验用户发卡 ...
- WIN32/API/SDK/MFC四者之间的联系和区别
上面大家都说Win32是一个子系统,这个当然是对的,不过我们有时候我们所说Win32通俗的就是指32位的Windows系统,从 windows95/98到NT/2000/XP都是32位Windows. ...
- iOS ReactiveCocoa简单使用笔记
涉及对象: 两个输入框,一个按钮. 代码功能: 随时监测输入框内容的长度变化,并在输入内容不符合预设要求时,立即改变输入框背景色. 在两个输入框的内容都符合预设要求时,按钮才可用. RACSignal ...
- DOTA 2 API(个人资料)
获取个人资料 http://wiki.teamfortress.com/wiki/WebAPI/GetPlayerSummaries 获取个人库存 http://wiki.teamfortress.c ...
- php_codesninffer phpcs用法学习使用:
18:34 2016/1/12php_codesninffer phpcs用法学习使用:可以加一个参数设置结果输出为各种格式:如source格式:$ phpcs -s --report=source ...