Computer Science
Write a program to accept a filename from the user and display all the lines from the file which contain Python comment character '#'.
Python Data Handling
3 Likes
Answer
Let the file "notes.txt" include the following sample text:
Welcome to the Garden of Dreams
#where the ordinary becomes extraordinary
#the impossible becomes possible.
file_name = input("Enter the filename: ")
file = open(file_name, 'r')
lines = file.readlines()
for line in lines:
if '#' in line:
print(line)
file.close()
Output
Enter the filename: notes.txt
#where the ordinary becomes extraordinary
#the impossible becomes possible.
Answered By
1 Like
Related Questions
Write a function to insert a sentence in a text file, assuming that text file is very big and can't fit in computer's memory.
Write a program to read a file 'Story.txt' and create another file, storing an index of 'Story.txt', telling which line of the file each word appears in. If word appears more than once, then index should-show all the line numbers containing the word.
Reading a file line by line from the beginning is a common task. What if you want to read a file backward ? This happens when you need to read log files. Write a program to read and display content of file from end to beginning.
Write a Python program to display the size of a file after removing EOL characters, leading and trailing white spaces and blank lines.