|
发表于 2019-9-15 21:49:25
|
显示全部楼层
- def file_view(file_name, line_num):
- if line_num.strip() == ':':
- begin = '1'
- end = '-1'
-
- (begin, end) = line_num.split(':')#因为你输入的是':',所以begin = '',end = ''
- if begin == '':
- begin = '1'#则begin = 1
- if end == '':
- end = '-1' #end = -1
- if begin == '1' and end == '-1':#条件满足
- prompt = '的全文'#则prompt = '的全文'
- elif begin == '1':
- prompt = '从开始到%s' % end
- elif end == '-1':
- prompt = '从%s到结束' % begin
- else:
- prompt = '从第%s行到第%s行' % (begin, end)
- print('\n文件%s%s的内容如下:\n' % (file_name, prompt)) #这边打印的是 文件……的全文的内容如下:
- begin = int(begin) - 1 # 输入的是':',说明要打印全文,begin = 1 ,但是序列的第一个是 0,则begin - 1 = 0
- end = int(end) #同上要打印全文,end = -1
- lines = end - begin #lines = -1
- f = open(file_name)
-
- for i in range(begin): # 用于消耗掉begin之前的内容(这段小甲鱼注释的,是为了当不是要打印全文时,将要打印的部分的‘之前的内容消耗’)
- f.readline()
- if lines < 0:#只有当要打印全文是 lines 才会 < 0
- print(f.read()) # 开始打印全文
- else:
- for j in range(lines):
- print(f.readline(), end='')
-
- f.close()
- file_name = input(r'请输入要打开的文件(C:\\test.txt):')
- line_num = input('请输入需要显示的行数【格式如 13:21 或 :21 或 21: 或 : 】:')
- file_view(file_name, line_num)
复制代码 |
|