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

Go Ad-free

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 has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo