python 核心编程第九章练习题

9–1. 文件过滤. 显示一个文件的所有行, 忽略以井号( # )开头的行. 这个字符被用做Python , Perl, Tcl, 等大多脚本文件的注释符号.

附加题: 处理不是第一个字符开头的注释.


def readFile():
    fi = open('D:/test.txt', 'r')
    listFile = []
    for eachLine in fi:
        if '#' not in eachLine:
            listFile.append(eachLine)
        else:
            id = eachLine.index('#')
            listFile.append(eachLine[:id])
    for i in listFile:
        print(i, end ='')
    fi.close()
    
readFile()

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

def visitFile():
    fileName = input('Please input the file name you wanna visit:')
    nLine = int(input('Please input the line you wanna visit:'))
    fi = open(fileName)
    for eachLine in fi:
        if nLine:
            print(eachLine, end = '')
            nLine -= 1
        else:
            break
    fi.close()


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

def countLine():
    fileName = input('Please input the file name:')
    fi = open(fileName)
    n = 0
    for eachLine in fi:
        n += 1
    print(n)
    fi.close()

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

def showLine():
    fileName = input('Please input the file name:')
    with open(fileName,'r') as fi:
        i=1
        for eachLine in fi:
            print(eachLine, end = '')        
            if not i%25:
               os.system('pause')
            i+=1


9–6. 文件比较. 写一个比较两个文本文件的程序. 如果不同, 给出第一个不同处的行号和列号.

def cmp_file():
    f1 = open('test1.txt', 'r')
    f2 = open('test2.txt', 'r')
    fo = zip(f1,f2)
    Ln = 1
    for (line1, line2) in fo:
        if line1 == line2:
            pass
        else:
            print('Ln:%s' %Ln, end = '  ')
            Col = 1
            for (a,b) in zip(line1,line2):
                if a == b:
                    Col += 1
                else:
                    print('Col:%s' %Col) 
                    break
        Ln += 1                        
    f1.close()
    f2.close()


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

def parse_file():
    parse = {}
    with open(r'C:\Windows\win.ini') as file:
        for line in file:
            if line.startswith(';'):
                continue
            if line.startswith('['):
                item = []
                name = line[1:line.rfind(']')]
                parse.setdefault(name,item)
                continue
            if '=' in line:
                item.append(line.strip())
    print(parse)

9–15. 复制文件. 提示输入两个文件名(或者使用命令行参数). 把第一个文件的内容复制到第二个文件中去.

def copy_file():
    orgLine = ''
    with open(r'test1.txt') as orgFile:
        for eachLine in orgFile:
            orgLine = orgLine+eachLine
    with open('test2.txt', 'a') as destFile: 
        destFile.write(orgLine)
                     
copy_file()

9–16. 文本处理. 人们输入的文字常常超过屏幕的最大宽度. 编写一个程序, 在一个文本
文件中查找长度大于 80 个字符的文本行. 从最接近 80 个字符的单词断行, 把剩余文件插入到
下一行处.

程序执行完毕后, 应该没有超过 80 个字符的文本行了.


def len80():
    with open(r'test1.txt',) as fi:
        with open('tmp.txt', 'w') as ft:
            for eachLine in fi:
                le = len(eachLine)
                if le > 80:
                    lineList = list(eachLine)
                    count = int(len(lineList) / 80)
                    print(count)
                    for i in range(count):
                        ft.write(''.join(lineList[:80]))
                        ft.write('\n')
                        lineList = lineList[80:]
                    ft.write(''.join(lineList))
                else:
                    ft.write(eachLine)
    with open(r'tmp.txt') as ft:
        with open('test1.txt', 'r+') as fi:
            for i in ft:
                fi.write(i)
    os.remove('tmp.txt')



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值