115k views
3 votes
Write a program that asks the user for the name of a file. The program should display the contents of the file with each line preceded with a line number followed by a colon. The line numbering should start at 1. (You can create a file and populate it with some data, then run your program to open that file and display the contents line by line with the number of the line preceding the line data)

User Yokiijay
by
4.4k points

2 Answers

2 votes

Final answer:

To write a program that asks the user for the name of a file and displays its contents with line numbers, you can use a programming language like Python.

Step-by-step explanation:

To write a program that asks the user for the name of a file and displays its contents with line numbers, you can use a programming language like Python. Here's an example program:

filename = input("Enter the name of the file: ")

try:
with open(filename, 'r') as file:
lines = file.readlines()
for i, line in enumerate(lines, 1):
print(f'{i}: {line}')
except FileNotFoundError:
print("File not found.")

In this program, the user is prompted to enter the name of a file. The program then attempts to open the file and read its contents. Each line is printed with a line number (starting from 1).

User Reena Verma
by
4.6k points
3 votes

Answer:

Step-by-step explanation:

The following program is written in Python. It asks the user for the file name (which needs to be in the same directory as the program) and reads the file. It then splits it by lines and saves it into an array. Then it loops through the array, printing each line with its corresponding line number.

file_name = input("File Name: ")

f = open(file_name, 'r')

lines = f.read().split('\\')

for line in lines:

print(str(lines.index(line) + 1) + ': ' + line)

Write a program that asks the user for the name of a file. The program should display-example-1
User RockerBOO
by
4.1k points