194k views
0 votes
Write a program that allows the user to navigate the lines of text in a file. The program should prompt the user for a filename and input the lines of text into a list. The program then enters a loop in which it 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 line associated with that number.

It should be like as this sample run follows.

Enter the input file name: quotes.xtxt
I cannot open the file quotes.xtxt - Please check the name and try again.
Enter the input file name: quotes.txt
The file has 16 lines.
Enter a line number [0 to quit]: 1
1: Hakuna Matata!
Enter a line number [0 to quit]: -1
Try again. Line number must be between 0 and 16
Enter a line number [0 to quit]: 16
16: Just keep swimming!
Enter a line number [0 to quit]: 17
Try again. Line number must be between 0 and 16
Enter a line number [0 to quit]: 5
5: It's kind of fun to do the impossible.
Enter a line number [0 to quit]: A
Try again. Please enter a number between 0 and 16
Enter a line number [0 to quit]: $
Try again. Please enter a number between 0 and 16
Enter a line number [0 to quit]: 4
4: To infinity and beyond!
Enter a line number [0 to quit]: 0

1 Answer

3 votes

Answer:

Step-by-step explanation:

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

inputfile=open(iname,'r')

lines=[]

for line in inputfile:

lines.append(line)

inputfile.close()

print("The file has ",len(lines)," lines")

while True:

linenumber=int(input("Enter the line number or 0 to quit: "))

if linenumber==0:

break

elif linenumber > len(lines):

print("Error: line number must be less than ", len(lines))

else:

print(linenumber, " : ", lines[linenumber - 1])

User YotKay
by
4.3k points