Python 3.6 Write a program to create a file containing a series of integers, nam
ID: 3848472 • Letter: P
Question
Python 3.6
Write a program to create a file containing a series of integers, named numbers txt. The program is to calculate the average of all the numbers stored in the file. It also must handle the following exceptions: It should handle any FileNotFoundError exceptions that are raised when the file is not available. It should handle any IOError exceptions that are raised when the file is opened and data is read from it. It should handle any ValueError exceptions that are raised when the items that are read from the file are converted to a number. It should handle any ZeroDivisionError exceptions that are raised when the file is empty. Include finally clause in your program. Revised the program which creates a data file named students.txt for five names and corresponding scores. It then reads and displays the student file with its average scores.Explanation / Answer
The python programming code for the program that has a file containing series of integers named numbers.txt.the program is to calculate the average of all numbers stored in a file which handles the following exceptions:
1)FileNotFoundError
2)IOError
3)ValueError
4)ZeroDivisionError
it includes finally clause at the end of the program.the programming code is:
def main():
total = 0.0
length = 0.0
average = 0.0
try:
# to Get the name of a file
filename = input('Enter a file name: ')
# to Open the file which we enters
infile = open(filename, 'r')
#Read the file contents
contents = infile.read()
#Display the file contents
print(contents)
#Read values from file and calculate average
for line in infile:
amount = float(line)
total += amount
length = length + 1
average = total / length
#Close the file
infile.close()
#Print the amount of numbers in file and average of entered numbers
print('There were ', length, ' numbers in the file.' )
print(format(average, ',.2f'))
except IOError:
print('An error occurred trying to read the file.')
except ValueError:
print('Non-numeric data found in the file')
except FileNotFoundError:
print('an error that is file not found')
except ZeroDivisionError:
print('zero division error occured')
finally:
print('finally clause is executed')
main()
the sample output for the program is:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.