SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:3 | ISBN:9780132576376 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.