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()