第九章练习

9-1文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做Python , Perl, Tcl, 等大多脚本文件的注释符号.
  附加题: 处理不是第一个字符开头的注释

#!/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()
View Code

9-2:文件访问. 提示输入数字 N 和文件 F, 然后显示文件 F 的前 N 行.

#!/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()
View Code
#!/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)
View Code

9–3.   文件信息. 提示输入一个文件名, 然后显示这个文本文件的总行数.

#!/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()
View Code

9–4.   文件访问. 写一个逐页显示文本文件的 程序. 提示输入一个文件名, 每次显示文本文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行.

#!/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()
View Code

9–7. 解析文件.    Win32 用户: 创建一个用来解析 Windows .ini 文件的程序. 

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
View Code
原文地址:https://www.cnblogs.com/augustyang/p/6845728.html