Python核心编程第二版第九章文件和输入输出(课后习题)----我的答案

本文介绍了Python编程中关于文件和输入输出的实战练习,包括过滤掉以#号开头的行,按用户输入显示文件前N行,计算文件总行数,读取多个文件的考试成绩以及比较两个文本文件的差异。
摘要由CSDN通过智能技术生成

9-1.文件过滤。显示一个文件的所有行,忽略以#号开头的行。

f = open('./test.txt')
for eachLine in f:
    eachLine.strip()
    if not eachLine.startswith('#'):
        print(eachLine)
f.close()

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

num = int(raw_input('Input a number: '))
F = raw_input('Input a file name: ')
f = open(F)
for eachLine in range(num):
    print(f.readline())
f.close()

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

F = raw_input('Input a file name: ')
f = open(F)
print(len(f.readlines()))
f.close()
9-4.文件访问,写一个逐页显示文本文件的程序。提示输入一个文件名,每次显示文本文件的25行,暂停并向用户提示‘按任意键继续’,按键后继续执行。
#-*- coding:utf-8 -*-
import os
F = raw_input('Input a file name: ')
f = open(F)
print('Press any key to continues')
n = 0
for eachPage in f:
    print(eachPage)
    n += 1
    if n == 25:
        n = 0
        os.system('pause')

f.close()

9-5.考试成绩,改进你的考试成绩问题,要求能从多个文件中读入考试成绩。

f = open('test.txt','r')
scores = []
for i in f:
    if 0 <= int(i.strip()) <= 00:
        scores.append(int(i.strip()))
    if int(i.strip())<60:
         print 'score is F' ,i
    elif 60<=int(i.strip())<=69:
         print 'score is D',i
    elif 70<=int(i.strip())<=79:
         print 'score is C',i
    elif 80<=int(i.strip())<=89:
         print 'score is B',i
    elif 90<=int(i.strip())<=100:
         print 'score is A',i
    else:
         print 'score wrong,please input again',i
f.close()
print 'average score is %f' %(sum(scores)//len(scores)) 

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

f1 = open('test.txt')
f2 = open('test1.txt')
lin = 1#定义行等于1
for (i, j) in zip(f1, f2):
    if i == j:
        pass
    else:
        print(lin)
        col = 0#定义列
        for (a, b) in zip(f1, f2):
            if a == b:#列相等则加1
                col += 1
            else:
                print(col)#不相等输出列
                break
    lin += 1
f1.close()
f2.close()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值