Check sibling questions

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

Introducing your new favourite teacher - Teachoo Black, at only ₹83 per month


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 ‘#’’

CA Maninder Singh's photo - Expert in Practical Accounts, Taxation and Efiling

Made by

CA Maninder Singh

CA Maninder Singh is a Chartered Accountant for the past 12 years. He also provides Accounts Tax GST Training in Delhi, Kerala and online.