注明:
1、参考他人练习:http://www.cnblogs.com/balian/
2、自己的答案,并非官方。
9-1.文件过滤。显示一个文件的所有行,忽略以井号(#)开头的行。这个字符被用做Python,Perl,Tcl,等大多数脚本文件的注释符号。附加题:处理不是第一个字符开头的注释。
f = open('test3.txt') for line in f: line = line.strip() if line[0] != '#': print line
注:附加题看不懂,不知道什么意思。
9-2.文件访问。提示输入数字N和文件F,然后显示文件的前N行。
F = raw_input('Enter the name of file >>') N = raw_input('Enter the line of file >>') N = int(N) fileContent = open(F).readlines() for n in range(N): print fileContent[n - 1]
思路:readlines能将文本内容转化为一个列表,从而方便操作其中几行,最后用了for循环,以及切片,也可以用while。(最后抱歉没有关闭文件)
9-3.文件信息,提示输入一个文件名,然后显示这个文本文件的总行数。
filename = raw_input('Enter the name of the file>>') f = open(filename) fileline = f.readlines() print len(fileline) f.close()
9-4 文件访问。写一个逐页显示文本文件的程序,提示输入一个文件名,每次显示文本文件的25行,暂停并向用户提示“按任意键继续”,按键后继续执行。
#coding=utf-8 filename = raw_input('Enter the file name >>') fo = open(filename) def print25(fo): count = 0 while count < 25: print fo.readline(), count += 1 print25(fo) while (raw_input('Press any key to continue >>') != False): print25(fo) else: pass
PS,实现了简单效果,但有个bug,就是到文件结尾仍然会提示输入,无法停止。这里不知道怎么判断到了文章结尾,试着用f.tell()和len(f.read()),但f.tell()会加上行尾的\n。
9-6 文件比较。写一个比较两个文本文件的程序。如果不同,给出第一个不同处的行号和列号。
#coding=utf-8 f1_name = raw_input('Enter first file name >>') f2_name = raw_input('Enter 2nd file name >>') f1 = open(f1_name).readlines() f2 = open(f2_name).readlines() f1_range = len(f1) f2_range = len(f2) minRange = f1_range if f1_range < f2_range else f2_range #print minRange for n in range(minRange): if f1[n] != f2[n]: print n + 1 f1_list = len(f1[n]) f2_list = len(f2[n]) minList = f1_list if f1_list < f2_list else f2_list for m in range(minList): if f1[n][m] != f2[n][m]: print m + 1 break else: print m + 2 break else: print n + 2
PS,不好意思,又没关闭文件。
本章更多课后题可以看这个文章:http://hi.baidu.com/deathanybody/item/3dd9dd4889c82de3dc0f6c97