要求:
用户输入文件名
用户输入要显示的行数。
例如,输入【10:20】,显示第10行到第20行。
【:20】 从第一行到第20行
【10:】第10行到结尾
1 import os
2
3 def file_view(fileName,lineNum):
4 #判断文件是否存在
5 if fileName.strip()=="":
6 print("ERROR:请输入文件名")
7 return
8 if not os.path.exists(fileName):
9 print("ERROR:你输入的文件【%s】不存在" % fileName)
10 return
11 #打开文件
12 f=open(fileName)
13 f_total_lines=len(f.readlines())
14
15
16 #判断输入的行数格式是否正确
17 if lineNum.count(":") !=1:
18 print('ERROR:行数的格式不正确,":"有且只能出现一次')
19 return
20
21 #取得开始行和终了行
22 (startLine,endLine)=lineNum.split(":")
23 #“:”号前为空,从0第一行开始
24 if str(startLine.strip())=="":
25 startLine="1"
26
27 if str(endLine.strip())=="":
28 endLine=str(f_total_lines)
29
30 if (not startLine.isdigit()) or (not endLine.isdigit()):
31 print('ERROR:":"两侧必须是数字')
32 return
33 elif int(startLine)>int(endLine):
34 print('ERROR:起始行号>终止行号')
35 return
36
37 if int(startLine)>f_total_lines:
38 print('ERROR:起始行号大于文件最大行号')
39 return
40
41 #指针回到文件头部
42 f.seek(0,0)
43 index=0
44 for eachLine in f:
45 index+=1
46 if index >=int(startLine) and index<=int(endLine):
47 print(eachLine)
48 f.close()
49
50
51 fileName=input("请输入文件名(c:/test.txt):")
52 lineNum=input("请输入行号(例:10:20):")
53 file_view(fileName,lineNum)