|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
求大佬注释,尤其是if判断句和strip的使用不太看能懂、还有为什么使用1与-1呢,是有什么特殊含义。?
- def file_view(file_name, line_num):
- if line_num.strip() == ':':
- begin = '1'
- end = '-1'
-
- (begin, end) = line_num.split(':')
- if begin == '':
- begin = '1'
- if end == '':
- end = '-1'
- if begin == '1' and end == '-1':
- 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
- end = int(end)
- lines = end - begin
- f = open(file_name)
-
- for i in range(begin): # 用于消耗掉begin之前的内容
- f.readline()
- if 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)
复制代码
- def file_view(file_name, line_num):
- if line_num.strip() == ':': #strip()是去除字符串前后的空格的,若果输入的只有一个冒号,则是打印全文
- begin = '1' #第1行好理解
- end = '-1' #把行尾标志设为-1,其实也可以设成其他负数,没有影响,
-
- (begin, end) = line_num.split(':') #.split(':')以冒号为界把line_num分成2部分
- if begin == '': #前面为空则是从开头,所以begin设为1
- begin = '1'
- if end == '': #后面为空则是到结尾,end设为-1
- end = '-1'
- if begin == '1' and end == '-1': #根据选择设定打印的文字
- 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 #python从0开始,人类习惯从1开始,所以要开始行要减1
- end = int(end)
- lines = end - begin #计算一共要打印多少行,如果是到行尾,end等于-1,则lines无论如何小于0
- f = open(file_name)
-
- for i in range(begin): # 用于消耗掉begin之前的内容,没读一行指针指向下一行,这样可以把指针置于开始行,begin为0,则指针在开始不动
- f.readline()
- if lines < 0: #如果小于0,则是打印到文件尾,用read()从当前指针一撸到底就达到目的了
- print(f.read())
- else:
- for j in range(lines): #如果结尾指定了行数,则按计算的行数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)
复制代码
|
|