Write a program to display all the records in a file along with line/record number

Python program that displays all the records in a file along with their line numbers:

def display_records_with_line_numbers(filename):
    try:
        with open(filename, 'r') as file:
            for line_number, line in enumerate(file, start=1):
                print(f"Line {line_number}: {line.rstrip()}")

    except FileNotFoundError:
        print(f"File '{filename}' not found.")


filename = input("Enter the filename: ")
display_records_with_line_numbers(filename)

 

When you run the program, it prompts you to enter the filename. You can provide the name of the file for which you want to display the records along with their line numbers. The program opens the file in read mode and uses enumerate to iterate over each line, starting from line number 1.

For each line, it prints the line number along with the line content after removing any trailing newline character using rstrip().


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *