第九章练习
9-1文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做Python , Perl, Tcl, 等大多脚本文件的注释符号.
附加题: 处理不是第一个字符开头的注释
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python def checkfile(): with open('D:/123/test.txt','rb') as f: for i in f: #print i if i.startswith('#'): continue else: print i, checkfile()
9-2:文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env pyhon import sys def openfile(): filename=sys.argv[1] fileline=int(sys.argv[2]) #print type(fileline) #print fileline f=open(filename,'rb') n=0 for eachline in f: print eachline, n+=1 if n>=fileline:break f.close() openfile()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env pyhon def outputfiles3(filename,fileline): f=open(filename,'r') n=0 for eachLine in f: print eachLine, n+=1 if n>=fileline:break f.close() outputfiles3('1.py',10)
9–3. 文件信息. 提示输入一个文件名, 然后显示这个文本文件的总行数.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python # -*- coding: utf-8 -* # def count(): filename=raw_input('filename: ') with open(filename,'rb') as f: print filename, '一共有', len(f.readlines()),'行' count()
9–4. 文件访问. 写一个逐页显示文本文件的 程序. 提示输入一个文件名, 每次显示文本文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#!/usr/bin/env python #_*_ encoding:utf-8 _*_ def test(): filename=raw_input('请输入文件名: ') with open(filename,'rb') as f: for i,item in enumerate (f): if (i+1)%3==0: raw_input('按键后继续执行.....') print item, test()
9–7. 解析文件. Win32 用户: 创建一个用来解析 Windows .ini 文件的程序.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
section={} with open('C:/windows/win.ini', 'rb') as f: for item in f: if item.startswith(';'): continue if item.startswith('['): data={} name = item[1:item.rfind(']')] section[name]=data continue if item.count('=') > 0 and data!=None: index = item.find('=') key = item[0:index] value=item[index+1:].strip() data[key]=value print section
posted on 2017-05-12 15:25 augustyang 阅读(156) 评论(0) 编辑 收藏 举报