English

Write a program to accept a filename from the user and display all the lines from the file which contain python comment character '#'.

Advertisements
Advertisements

Question

Write a program to accept a filename from the user and display all the lines from the file which contain python comment character '#'.

Code Writing
Advertisements

Solution

filename = input("Enter filename: ")

try:
    with open(filename, "r") as file:
        for line_number, line in enumerate(file, start=1):
            if "#" in line:
                print(line_number, line.rstrip("\n"))
except FileNotFoundError:
    print("File does not exist.")

The program displays both the line number and the matching line.

shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Data File Handling - EXERCISE [Page 146]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 7 Data File Handling
EXERCISE | Q 20. | Page 146
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×