Computer Science
Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
Then the function should display the output as :
This is a sample file.
The file contains many sentences.
Python File Handling
3 Likes
Answer
The file "NOTES.TXT" contains:
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.
def Show_words(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.strip().split()
if len(words) == 5:
print(line.strip())
Show_words('NOTES.TXT')
Output
This is a sample file.
The file contains many sentences.
Answered By
2 Likes
Related Questions
Write a function to search and display details of all trains, whose destination is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file "Book.dat"
Write a Python program to read a given CSV file having tab delimiter.
Write a Python program to write a nested Python list to a csv file in one go. After writing the CSV file read the CSV file and display the content.