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

 

Answer:

input_filename=input("Enter a file name: ")

try:

f=open(input_filename+".txt",'r')

l=f.readlines()

for line in l:

if line[0]=='#':

print(line)

 

except:

print("File not found")

Question 2-Write a program to accept - Teachoo.JPG

Remove Ads

Transcript

Question 2 Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character ‘#’. Taking a user input for the filename as ‘input_filename’ reading all the lines in the text file and assigning it to ‘l’ Checking if the first character of a line is ‘#’ Output opening the text file in read mode and assigning it to file_object ‘f’ Iterating through each line in ‘l’ and assigning it to ‘line’ Prints the line which starts with ‘#’’

Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.