《python核心编程第九章》由会员分享,可在线阅读,更多相关《python核心编程第九章(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 n
2、ame: ).strip()n = 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 =
3、 open(os.path.join(path,f),r)read_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 Lin
4、e: %d - Row: %d %(i+1,j+1)breakfor i in range(1,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(pat
5、h,fn)for section in cp.sections():print cp.items(section)for 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_(na
6、me)nature = dir(obj)for item in nature:print name: %s ,type: %s ,value: %s %(item,type(getattr(obj, item),getattr(obj, item)import osimport gcdef findDoc(path):99. Python 文档字符串. 进入Python 标准库所在的目录. 检查每个 .py 文件看是否有_doc_字符串,如果有, 对其格式进行适当的整理归类. 你的程序执行完毕后, 应该会生成一个漂亮的清单. 里边列出哪些模块有文档字符串, 以及文档字符串的内容. 清单最后附上
7、那些没有文档字符串模块的名字.附加题: 提取标准库中各模块内全部类(class)和函数的文档.without = gc.disable()for root,dirs,files in os.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:witho
8、ut.append(fname)gc.enable()print Without _doc_:n%s %withoutimport ConfigParserdef financial():910. 家庭理财.创建一个家庭理财程序. 你的程序需要处理储蓄, 支票, 金融市场, 定期存款等多种帐户.为每种帐户提供一个菜单操作界面, 要有存款, 取款, 借,贷等操作. 另外还要提供一个取消操作选项. 用户退出这个程序时相关数据应该保存到文件里去(出于备份的目的,程序执行过程中也要备份.)prompt =(S)avings(C)heck(F)inancial market(D)eposit(E)xit
9、Enter your selection:function =(s)avings(d)raw(b)orrow(l)oanEnter your selection:account = s:Savings,c:Check,f:Financial,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:prin
10、t Welcome %s business! %accountenter.lower()section = accountenterselect = raw_input(function).strip()0.lower()if select in 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
11、 c .n)if cancel = c: return Falseelse: fp = open(FamilyAccount.ini,w)cf.write(fp)fp.close()elif enter = e:return Falseelse: print Invalid operation,try again!def UrlBookmark():911. Web 站点地址.a) 编写一个 URL 书签管理程序.使用基于文本的菜单,用户可以添加, 修改或者删除书签数据项. 书签数据项中包含站点的名称, URL 地址, 以及一行简单说明(可选). 另外提供检索功能,可以根据检索关键字在站点名称
12、和 URL 两部分查找可能的匹配. 程序退出时把数据保存到一个磁盘文件中去;再次执行时候加载保存的数据.prompt = URL bookmark:(A)dd(H)ttp(M)odify(D)elete(S)earch(Q)uitEnter your selection:function = a : add,m : modify,d : delete,s : search,h : addHttpwhile True:slt = raw_input(prompt).strip()0.lower()if q = slt: return Falseif slt in amdsh:functionsl
13、t()import ConfigParserdef add():urlname = raw_input(Please enter URL name:).strip()url = raw_input(Please enter URL:).strip()cf = ConfigParser.ConfigParser()cf.read(Bookmark.ini)try: cf.add_section(Bookmark)except Exception,e: print ecf.set(Bookmark,urlname,url)fp = open(Bookmark.ini,w)cf.write(fp)f
14、p.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 name:).strip()url = raw_input(Please enter URL :).strip()if 0 = len(url) or 0 = len(urlname): return Falsetry: lop
15、= 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.close()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:).s