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?
