Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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, "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 filenameStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started