In: Computer Science
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.
An example file and the program input and output is shown below:
example.txt
Line 1.
Line 2.
Line 3.
Enter the input file name: example.txt The file has 3 lines. Enter a line number [0 to quit]: 2 2 : Line 2. The file has 3 lines. Enter a line number [0 to quit]: 4 ERROR: line number must be less than 3. The file has 3 lines. Enter a line number [0 to quit]: 0
Make sure the program gracefully handles a user entering a line number that is too high.
Working code implemented in Python and appropriate comments provided for better understanding.
Source Code:
# Take the input file name
inName = input("Enter the input file name: ")
# Open the input file and read the text
inputFile = open(inName, 'r')
lines = list()
for line in inputFile:
lines.append(line)
# Loop for line numbers from the user until she enters 0
# and prints the line's number followed by the line
while True:
print("The file has", len(lines), "lines.")
if len(lines) == 0:
break
lineNumber = int(input("Enter a line number [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])
Code Screenshots: