最近看了一本叫做《简明Python》的书。

书中最后竟然有这么个小实例。

其中用到了python中的词典和Cpickle存储。还有面向对象编程的思想(os:让一个没有对象的人面向对象简直惨)


#!/usr/bin/python
#Filename:Contact_address.py

import cPickle as p
import os
import sys
filename='addressbook.data'

class Person:
	def __init__(self,name,PhoneNum,address):
		self.name=name
		self.PhoneNum=PhoneNum
		self.address=address

def update():
	content=raw_input('please input similar to leo,18636658660,leo@outlook.com>>\n')
	con=content.split(',')
	context=Person(con[0],con[1],con[2])
	f=file(filename)
	conlist=p.load(f)
	conlist[context.name]=context.PhoneNum+','+context.address
	f=file(filename,'w')
	p.dump(conlist,f)
	f.close()
	del conlist
	
#	f=file(filename)
#	conlist=p.load(f)
#	print conlist

def delete():
	f=file(filename)
	conlist=p.load(f)
	print conlist
	d=raw_input("please input the person's name you want to delete\n")
	del conlist[d]
	print conlist
	f=file(filename,'w')
	p.dump(conlist,f)
	f.close()
	del conlist

def select():
	f=file(filename)
	conlist=p.load(f)
#	print conlist
	s=raw_input("please input the person's name you want to select\n")
	if(s in conlist):
		print s,':',conlist[s]
	else:
		print '%s is not exist'%s 

def main():
	while True:
		menu=raw_input('''''
			1.select
			2.update
			3.delete
			x.exit
			------>\n''')
		if menu=='1':
			select()
		elif menu=='2':
			update()
		elif menu=='3':
			delete()
		elif menu=='x':
			sys.exit()
		else:
			print"do not have this option,please try again"
		
if os.path.exists('addressbook.data'):
	main()
else:
	f=file('addressbook.data','w')
	conlist={'leo':'18636658660,leo@outlook.com'}
	p.dump(conlist,f)
	f.close()
	del conlist
	main()

这大体就是这样

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐