Question: python please Consider the following function: def count_words (filename): input_file = open(filename, r) words = input_file.read().split() input_file.close() return len (words) The above function takes a

python please Consider the following function: def count_words (filename): input_file = open(filename,python please

Consider the following function: def count_words (filename): input_file = open(filename, "r") words = input_file.read().split() input_file.close() return len (words) The above function takes a filename as a parameter and returns the number of words in the file. You can assume that words are separated by whitespace. Modify the above function and use a try-except-else block to handle any exceptions that may occur. If the parameter filename is an empty string, the function should return an error message "ERROR: Invalid filename!". If the file cannot be opened, the function should return "ERROR: The file '...' does not exist." where ... indicates the filename. Note: remember to close the file properly if the file can be opened. You *must* use the try... except syntax and handle the FileNotFoundError in your solution. For example: Test Result print(count_words('lincoln. txt')) 277 print(count_words ('input_unknown.txt')) ERROR: The file 'input_unknown.txt' does not exist. print(count_words('')) ERROR: Invalid filename

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!