Computer Science
Write a method in python to read lines from a text file MYNOTES.TXT, and display those lines, which are starting with an alphabet 'K'.
Answer
Let the file "MYNOTES.TXT" include the following sample text:
Kangaroo is a mammal native to Australia.
Lion is a large carnivorous.
Koala is an arboreal herbivorous.
Elephant is a large herbivorous mammal.
def display_lines(file_name):
with open(file_name, 'r') as file:
line = file.readline()
while line:
if line.strip().startswith('K'):
print(line.strip())
line = file.readline()
display_lines("MYNOTES.TXT")
Output
Kangaroo is a mammal native to Australia.
Koala is an arboreal herbivorous.
Related Questions
Write a program that copies one file to another. Have the program read the file names from user ?
Write a program that appends the contents of one file to another. Have the program take the filenames from the user.
Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 4 characters.
Write a program that reads characters from the keyboard one by one. All lower case characters get stored inside the file LOWER, all upper case characters get stored inside the file UPPER and all other characters get stored inside file OTHERS.