在给定行号的文本文件中打印行

2024-03-29 05:03:09 发布

您现在位置:Python中文网/ 问答频道 /正文

对于下面的问题,我无法使用while循环语句。这是给a的txt文件. 在

'Write a program that allows the user to navigate through the lines of text in any text file. The program prompts the user for a filename and copies the lines of text from the file into a list. The program then prints the number of lines in the file and prompts the user for a line number. Actual line numbers range from 1 to the number of lines in the file. If the input is 0, the program quits. Otherwise, the program prints the text in that line number.'

请看我的代码。在

enterfile = input("Enter the file name: ")
file = open(enterfile, 'r')
linecount = 0
for line in file:
    linecount = linecount + 1
print("The number of lines in this txt. file is", linecount)
linenum = 0
while True:
num = int(input("Please enter a line number or press 0 to quit: "))
if num >=1 and num <= linecount:
    file = open(enterfile, 'r')
    for lines in file:
        linenum = linenum + 1
        if linenum == num:
            print(lines)
else:
    if num == 0:
        print("Thanks for using the program")
        break

运行程序时,输入行号后行号不会打印。在

显然,我没有正确地使用while循环。有人能告诉我我做错了什么吗?我可以在这里使用def函数吗?在

谢谢!在


Tags: ofthetextinnumberforlineprogram
3条回答

While True:循环内移动linenum = 0行。在

当程序重新进入循环时,linenum变量必须重置为0(linenum = 0)。否则,linenum变量将始终递增,并且其值大于num,并且永远不会触发if语句以该数字打印行。在

循环中包含linenum = 0的代码

enterfile = input("Enter the file name: ")
file = open(enterfile, 'r')
linecount = 0

for line in file:
    linecount = linecount + 1

print("The number of lines in this txt. file is", linecount)

while True:
    linenum = 0

    num = int(input("Please enter a line number or press 0 to quit: "))
    if num >=1 and num <= linecount:
        file = open(enterfile, 'r')
        for lines in file:
            linenum = linenum + 1
            if linenum == num:
                print(lines)
    else:
        if num == 0:
            print("Thanks for using the program")
            break

替代方法:

^{pr2}$

函数的作用是:返回一个包含行的列表,然后根据用户输入打印索引值。在

file = input("Enter the file name: ")
text_file = open(file, "r")
lines = text_file.readlines()
print (len(lines))
while True:
    linenumber = int(input("Please enter a line number or press 0 to quit:  "))
    if linenumber == 0:
        print("Thanks for using the program")
        break
    elif 1 <= linenumber <= len(lines) :
      print (lines[linenumber- 1])
    else:
        print("Please enter valid line number")
text_file.close()

似乎你在输入后错过了作业的第一步

copies the lines of text from the file into a list

有了它,你就会

with open(enterfile) as f:
    lines = [line.rstrip() for line in f]
# continue on from here 

现在,忘记您有一个文件,您可以使用len(lines)和{}分别获得总行数和特定行数

相关问题 更多 >