Answered step by step
Verified Expert Solution
Link Copied!

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

image text in transcribedpython 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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Spatial Databases A Tour

Authors: Shashi Shekhar, Sanjay Chawla

1st Edition

0130174807, 978-0130174802

More Books

Students also viewed these Databases questions

Question

Psychological, financial, and career counseling.

Answered: 1 week ago