44.9k views
5 votes
#Write a function called "angry_file_finder" that accepts a #filename as a parameter. The function should open the file, #read it, and return True if the file contains "!" on every #line. Otherwise the function should return False. # #Hint: there are lots of ways to do this. We'd suggest using #either the readline() or readlines() methods. readline() #returns the next line in the file; readlines() returns a #list of all the lines in the file. #Write your function here!

1 Answer

1 vote

Answer:

I am writing a Python function:

def angry_file_finder(filename): #function definition, this function takes file name as parameter

with open(filename, "r") as read: #open() method is used to open the file in read mode using object read

lines = read.readlines() #read lines return a list of all lines in the file

for line in lines: #loops through each line of the file

if not '!' in line: #if the line does not contains exclamation mark

return False # returns False if a line contains no !

return True # returns true if the line contains exclamation mark

print(angry_file_finder("file.txt")) call angry_file_finder method by passing a text file name to it

Step-by-step explanation:

The method angry_file_finder method takes a file name as parameter. Opens that file in read mode using open() method with "r". Then it reads all the lines of the file using readline() method. The for loop iterates through these lines and check if "!" is present in the lines or not. If a line in the text file contains "!" character then function returns true else returns false.

There is a better way to write this method without using readlines() method.

def angry_file_finder(filename):

with open(filename, "r") as file:

for line in file:

if '!' not in line:

return False

return True

print(angry_file_finder("file.txt"))

Above method opens the file in read mode and just uses a for loop to iterate through each line of the file to check for ! character. The if condition in the for loop checks if ! is not present in a line of the text file. If it is not present in the line then function returns False else it returns True. This is a more efficient way to find a character in a file.

User Nick Partridge
by
5.1k points