繁体   English   中英

Python:如何在收到用户输入后从文件打印行

[英]Python: How to print lines from a file after receiving user input

忍受我是编程新手。 我正在尝试创建一个程序,该程序将从文件中打印特定行的行,等待用户输入,然后打印另一个特定行等。从本质上讲,一个打印行[1、2和3]的程序会询问用户作为输入,然后打印[4、5和6]行等。

具体来说,我仅表示外部文本文件中的某些行

我不知道该怎么做,实际上只能打印文件中的特定行。

lines = []
for line in enumerate(open("mathsquiz.txt" , "r")):
    lines.append(line)
    targetlines = [4, 5, 10, 11, 16, 17, 22, 23]
    for line in lines:
        if line[0] not in targetlines:
            print(line[1])

未测试,但尝试:

targetlines = [4, 5, 10, 11, 16, 17, 22, 23]
with open("mathsquiz.txt", "r") as f_in:
    for n, line in enumerate(f_in):
       if n in targetlines:
           print(line)

同样,未经测试,但应该可以工作:

while True:     
    s=input('enter lines separated by spaces:')     
    if s.strip()=='': break
    tgt=[int(e) for e in s.split()]
    print(tgt)
    with open("mathsquiz.txt", "r") as f_in:
        for n, line in enumerate(f_in):
            if n in tgt:
               print(line.rstrip())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM