《python核心编程第九章.pdf》由会员分享,可在线阅读,更多相关《python核心编程第九章.pdf(10页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、#-*-coding:utf-8-*-import ospath=os.getcwd()def filer(path,fname):91.文件过滤.显示一个文件的所有行,忽略以井号(#)开头的行.f=open(os.path.join(path,fname),r)for reader in f:if not reader.startswith(#):print readerf.close()def printLine(n,f):92.文件访问.提示输入数字 N 和文件 F,然后显示文件 F 的前 N 行.f=raw_input(Please enter file name:).strip()n
2、=int(raw_input(Please enter lines number:).strip()fopen=open(os.path.join(path,f),r)for reader in fopen:cont+=1if cont 25:cont=1raw_input(Please press any key to continue.)print readerfopen.close()def compareFile(f,f2):96.文件比较.写一个比较两个文本文件的程序.如果不同,给出第一个不同处的行号和列号.fopen_1=open(os.path.join(path,f),r)re
3、ad_1=fopen_1.readlines()fopen_2=open(os.path.join(path,f2),r)read_2=fopen_2.readlines()minNum=min(len(read_1),len(read_2)for i in range(minNum):minRow=min(len(read_1i),len(read_2i)for j in range(minRow):if cmp(read_1ij,read_2ij)!=0:print Differ contents Line:%d-Row:%d%(i+1,j+1)breakfor i in range(1,
4、abs(len(read_1)-len(read_2)+1):print Differ content Line:%d-Row:1%(minNum+i)fopen_1.close()fopen_2.close()import ConfigParserdef configFile(fn):97.解析文件.Win32 用户:创建一个用来解析Windows.ini 文件的程序.cp=ConfigParser.ConfigParser()cp.read(os.path.join(path,fn)for section in cp.sections():print cp.items(section)fo
5、r key in cp.options(section):print%s-%s=%s%(section,key,cp.get(section,key)cp.add_section(Name)cp.set(Name,kyrie,27)fp=open(os.path.join(path,fn),a)cp.write(fp)fp.close()def viewModul():name=raw_input(module name:)obj=_import_(name)nature=dir(obj)for item in nature:print name:%s,type:%s,value:%s%(it
6、em,type(getattr(obj,item),getattr(obj,item)import osimport gcdef findDoc(path):99.Python 文档字符串.进入 Python 标准库所在的目录.检查每个.py 文件看是否有_doc_字符串,如果有,对其格式进行适当的整理归类.你的程序执行完毕后,应该会生成一个漂亮的清单.里边列出哪些模块有文档字符串,以及文档字符串的内容.清单最后附上那些没有文档字符串模块的名字.附加题:提取标准库中各模块内全部类(class)和函数的文档.without=gc.disable()for root,dirs,files in o
7、s.walk(path):for fname in files:if fname.endswith(.py):try:obj=_import_(fname.replace(.py,)if obj._doc_:print fname.replace(.py,)+._doc_:nprint obj._doc_else:without.append(fname)except Exception,e:without.append(fname)gc.enable()print Without _doc_:n%s%withoutimport ConfigParserdef financial():910.
8、家庭理财.创建一个家庭理财程序.你的程序需要处理储蓄,支票,金融市场,定期存款等多种帐户.为每种帐户提供一个菜单操作界面,要有存款,取款,借,贷等操作.另外还要提供一个取消操作选项.用户退出这个程序时相关数据应该保存到文件里去(出于备份的目的,程序执行过程中也要备份.)prompt=(S)avings(C)heck(F)inancial market(D)eposit(E)xitEnter your selection:function=(s)avings(d)raw(b)orrow(l)oanEnter your selection:account=s:Savings,c:Check,f:F
9、inancial,d:Depositfun=s:savings,d:draw,l:loan,b:borrowcf=ConfigParser.ConfigParser()cf.read(FamilyAccount.ini)enter=raw_input(prompt).strip()0.lower()while True:if enter in scfd:print Welcome%s business!%accountenter.lower()section=accountenterselect=raw_input(function).strip()0.lower()if select in
10、sdbl:print Welcome%s business!%funselectkey=funselectmonkey=int(raw_input(Enter amount of money:).strip()cf.set(section,key,monkey)cancel=raw_input(Cancel,please press c.n)if cancel=c:return Falseelse:fp=open(FamilyAccount.ini,w)cf.write(fp)fp.close()elif enter=e:return Falseelse:print Invalid opera
11、tion,try again!def UrlBookmark():911.Web 站点地址.a)编写一个 URL 书签管理程序.使用基于文本的菜单,用户可以添加,修改或者删除书签数据项.书签数据项中包含站点的名称,URL 地址,以及一行简单说明(可选).另外提供检索功能,可以根据检索关键字在站点名称和 URL 两部分查找可能的匹配.程序退出时把数据保存到一个磁盘文件中去;再次执行时候加载保存的数据.prompt=URL bookmark:(A)dd(H)ttp(M)odify(D)elete(S)earch(Q)uitEnter your selection:function=a:add,m:
12、modify,d:delete,s:search,h:addHttpwhile True:slt=raw_input(prompt).strip()0.lower()if q=slt:return Falseif slt in amdsh:functionslt()import ConfigParserdef add():urlname=raw_input(Please enter URL name:).strip()url=raw_input(Please enter URL:).strip()cf=ConfigParser.ConfigParser()cf.read(Bookmark.in
13、i)try:cf.add_section(Bookmark)except Exception,e:print ecf.set(Bookmark,urlname,url)fp=open(Bookmark.ini,w)cf.write(fp)fp.close()import urllib2import osdef addHttp():prompt=Whether to create bookmark directory?Yes?please enter dir name.No?please press Enter key.urlname=raw_input(Please enter URL nam
14、e:).strip()url=raw_input(Please enter URL:).strip()if 0=len(url)or 0=len(urlname):return Falsetry:lop=urllib2.urlopen(url)except Exception,e:print endir=raw_input(prompt)if 0!=len(ndir):try:os.mkdir(ndir)except Exception,e:print eos.chdir(ndir)msg=lop.read()fp=open(urlname+.html,w)fp.write(msg)fp.cl
15、ose()def modify():string=Please enter url name:name=raw_input(string).strip()cf=ConfigParser.ConfigParser()cf.read(Bookmark.ini)if cf.has_option(Bookmark,name):print%s-%s%(name,cf.get(Bookmark,name)url=raw_input(Enter modified url:).strip()if 0=len(url):return Falsecf.set(Bookmark,name,url)fp=open(B
16、ookmark.ini,w)cf.write(fp)fp.close()else:print%s not existed!%namedef delete():string=Please enter URL name you want to delete:urlname=raw_input(string).strip()cf=ConfigParser.ConfigParser()cf.read(Bookmark.ini)if urlname in cf.options(Bookmark):cf.remove_option(Bookmark,urlname)print Deleted succes
17、sfully!else:print URL bookmark is not existing.def search():flag=0string=Please enter url name or link:url=raw_input(string).strip()cf=ConfigParser.ConfigParser()cf.read(Bookmark.ini)for op in cf.options(Bookmark):if url=op or url=cf.get(Bookmark,op):print Found:%s-%s%(op,cf.get(Bookmark,op)flag=1br
18、eakif 0=flag:print Not found,%s not existed!%urlimport pickleimport shelveimport timedef login():912.用户名和密码.回顾练习 7-5,修改代码使之可以支持上次登录时间.请参阅 time 模块中的文档了解如何记录用户上次登录的时间.另外提供一个系统管理员,它可以导出所有用户的用户名,密码(如果想要的话,你可以把密码加密),以及上次登录时间.prompt=-New user loginOld user loginAdminstrator loginExit login UI-fun=n:newUse
19、r,o:oldUser,a:adminwhile True:slt=raw_input(prompt).strip()0.lower()if slt=e:return Falseif slt not in noa:print Invalid selection,try agin!else:funslt()def newUser():#pickleinfo=print Welcome to the first login!name=raw_input(Please enter username:).strip()pwd=raw_input(Plase enter passward:).strip
20、()ltime=str(time.time()info=getInfo()for item in info:msg=item.split(:)if name=msg0:print User name have existed!return Falseinfo.append(name+:+pwd+:+ltime)storeInfo(info)#shelveprint Welcome to the first login!name=raw_input(Please enter username:).strip()pwd=raw_input(Plase enter passward:).strip(
21、)if name in getInfo():print User name have existed!return FalsestoreInfo(name,pwd)def oldUser():#pickleprint Welcome back!flag=0name=raw_input(Please enter username:).strip()pwd=raw_input(Plase enter passward:).strip()for item in getInfo():msg=item.split(:)if name=msg0 and pwd=msg1:if timer(float(ms
22、g2)4:print You already logged in at:%s.%(time.ctime(float(msg2)flag=1if 0=flag:print Username or pwd incorrect!#shelveprint Welcome back!name=raw_input(Please enter username:).strip()pwd=raw_input(Plase enter passward:).strip()sp=shelve.open(dbm)if name in sp.keys():if pwd=spname0:if timer(spname1)4
23、:print You already logged in at:%s.%(time.ctime(spname1)else:print Login successfully!spname1=time.time()else:print Pwd incorrect!else:print User name not existed!def admin():#pickleif 0=len(getInfo():print No user info!return Falseprint All user info:for item in getInfo():msg=item.split(:)print Nam
24、e:%s-Pwd:%s%(msg0,msg1)#shelveprompt=-Show all user infoDelete user info-enter=raw_input(prompt).strip()0.lower()sp=shelve.open(dbm)if 0=len(sp.keys():print No user info!return Falseif s=enter:print All user info:for key in sp.keys():print Name:%s-Pwd:%s%(key,spkey0)elif d=enter:user=raw_input(Pleas
25、e enter the user you want to delet:).strip()del spuserprint Delete successfullysp.close()#pickledef storeInfo(obj):fp=open(info.dat,w)pickle.dump(obj,fp)fp.close()def storeInfo(nm,pw):#shelvectm=time.time()sp=shelve.open(dbm)spnm=pw,ctmsp.close()print Register successfully!def getInfo():#picklefp=open(info.dat,a+)try:msg=pickle.load(fp)except Exception,e:msg=fp.close()return msg#shelvesp=shelve.open(dbm)return sp.keys()def timer(tm):return(time.time()-tm)/360
限制150内