Printing lines in a text file given line numbers

Tags: , , , ,



I am having trouble with a while loop statement for the question below. This is for a txt.file.

‘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.’

Please see my code.

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

When I run the program, the line number does not print after I enter a line number.

Obviously, I am not using the while loop correctly here. Can someone please tell me what I am doing wrong here? Can I possibly use a def function here?

Thanks!

Answer

Move line linenum = 0 inside the While True: loop.

The linenum variable must be reset to 0 (linenum = 0) when the program re-enters the loop. Otherwise the linenum variable will always keep being incremented and have a value that is greater than num and will never trigger the if statement to print the line at that number.

Your code with linenum = 0 in the loop:

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

Alternative method:

enterfile = input("Enter the file name: ")

with open(enterfile) as f:
    lines = [line.rstrip() for line in f]

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

while True:
    num = int(input("Please enter a line number or press 0 to quit: "))

    if num > 0 and num < len(lines) + 1:
        print(lines[num - 1]) 
    elif num == 0:
        print('Thanks for using the program.')
        break


Source: stackoverflow