Ask Question
13 April, 15:50

Read_file = open ('numbers. txt', 'r')

file_numbers = read_file. read ()

read_file. close ()

list_values = file_numbers. split ()

list_length = len (list_values)

for i in range (list_length):

list_values[i] = float (list_values[i])

List_sum = sum (list_values)

Average_value = (List_sum) / list_length

print (Average_value)

Problem:

Modify the program you wrote for Chapter 6 Exercise 6 so it handles the following

exceptions:

• It should handle IOError exceptions that are raised when the file is opened

and data is read from it by printing "Trouble opening file. Try again." and

not executing any more of the code.

• It should handle any ValueError exceptions that are raised when the items

that are read from the file are converted to a number by printing "File must have

only numbers. Try again." and not executing any more of the code.

+1
Answers (1)
  1. 13 April, 19:41
    0
    To do that, use exception handling

    Explanation:

    Try:

    read_file = open ('numbers. txt', 'r')

    file_numbers = read_file. read ()

    except IOError exceptions:

    print ("Trouble opening file. Try again")

    read_file. close ()

    list_values = file_numbers. split ()

    list_length = len (list_values)

    for i in range (list_length):

    list_values[i] = float (list_values[i])

    except ValueError:

    print ("File must have only numbers. Try again.")

    List_sum = sum (list_values)

    Average_value = (List_sum) / list_length

    print (Average_value)
Know the Answer?
Not Sure About the Answer?
Find an answer to your question ✅ “Read_file = open ('numbers. txt', 'r') file_numbers = read_file. read () read_file. close () list_values = file_numbers. split () ...” in 📘 Computers and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers