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

Here’s a Python program that accepts a filename from the user and displays all the lines from the file that contain the Python comment character ‘#’:

def display_comment_lines(filename):
    try:
        with open(filename, 'r') as file:
            for line in file:
                if '#' in line:
                    print(line.strip())

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


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

 

When you run the program, it will prompt you to enter the filename. You can provide the name of the file you want to search for comment lines in. The program opens the file in read mode and iterates over each line. It checks if the line contains the ‘#’ character using the in operator. If a line contains ‘#’, it is printed after stripping leading and trailing whitespace using strip().

Leave a Comment

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

Scroll to Top