Line Numbers
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.
Line Numbers Python code:
#Prompt and read the name of the file from the user
filename = input("Enter the name of the file: ")
#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.
try:
with open(filename, 'r') as file:
lines = file.readlines()
print("File Contents:")
for i, line in enumerate(lines, start=1):
# Print line number followed by a colon and the line content
print(f"{i}: {line.rstrip()}")
except FileNotFoundError:
print(f"File '{filename}' not found.")
except IOError:
print(f"An error occurred while reading the file '{filename}'.")
Data in "inFile.txt":
Hello
Python
welcome
to the python world
Executed Output:
Enter the name of the file: inFile.txt
File Contents:
1: Hello
2: Python
3: welcome
4: to the python world