如何打印请求的行数

时间:2016-11-20 20:25:33

标签: python

我正在尝试编写more函数的代码。

我需要:

  • 让程序暂停
  • 询问要打印的其他行数
  • 打印该行数
  • 再次停顿。

这是我到目前为止所拥有的:

import sys, fileinput
i=0
for line in fileinput.input():
    print(line.rstrip())
    i=i+1
    if i==20:
        what=input("<--Enter the # of additional lines you wish to print/q to Quit -->")
    if what=="q":
        exit()
    else:
        if str.isdigit(what):
            print(line.rstip[i:i+int(what)]

1 个答案:

答案 0 :(得分:0)

这是一种方法:

with open('file.txt') as f:
    fh = f.read()
    lines = fh.splitlines()
    lines_so_far = 0
    while lines_so_far < len(lines):
        batch_count = 0
        lines_requested = int(input('How many lines to print?'))
        for line in lines:
            print(line)
            batch_count += 1
            lines_so_far += 1
            if batch_count == lines_requested and lines_so_far < len(lines):
                printmore = input ('Print more lines: Y or N?')
                if printmore == 'Y':
                    batch_count = 0
                    lines_requested = int(input('How many lines?'))
                else:
                    lines_so_far = len(lines)
                    break
    print ('\n Done Printing')