I have a homework assignment that I am getting different results in my for loop of reading a file with numbers to get an average. Currently getting error: ZeroDivisionError: float division by zero. This is pointing to the line total_avg = total / count
Here’s the Python code:
"""
Develop a Python program that reads numerical data from a file, performs a series of calculations on the data,
and writes the results to an output file. The program should include robust exception handling to manage
potential errors during file operations and calculations.
1. Reading Data from a File:
- The program should read a file named input.txt. Use the sample input.txt file attached.
Each line in the file contains a single integer.
- The file may contain invalid lines (e.g., non-integer values). These lines should be skipped,
and an appropriate message should be logged. Use the invalid line sample input_invalid.txt file attached.
2. Performing Calculations:
- Compute the sum, average, maximum, and minimum of the valid integers read from the file.
- Ensure that the program handles cases where the file may be empty or contain no valid integers
by logging a suitable message.
3. Writing Results to a File:
- Write the calculated results (sum, average, maximum, and minimum) to a file named output.txt.
- Each result should be written on a new line in the format: Sum: <value>, Average: <value>, etc.
4. output.txt sample
Sum: 105
Average: 21.0
Maximum: 50
Minimum: -5
5. Exception Handling:
- Include exception handling to manage:
-- File not found errors.
-- Value errors when converting strings to integers.
-- Any other unforeseen errors.
- Log appropriate error messages for each type of exception.
Evaluation Criteria:
Correctness: The program correctly reads, processes, and writes data.
Robustness: The program handles exceptions and edge cases effectively.
Code Quality: The code is well-organized, commented, and follows best practices.
"""
def main():
# Initializing variables to 0 for the for loop section to get the average
total = 0.0
count = 0
input_file = open(r'/home/ed/files/Documents/School/Classes/ITEC2270-01_Application_Development/input.txt', 'r')
# Reading each line and placing that value in a variable
line1 = int(input_file.readline())
line2 = int(input_file.readline())
line3 = int(input_file.readline())
line4 = int(input_file.readline())
line5 = int(input_file.readline())
# Create a variable to store the sum of all the lines read above
total_sum = line1 + line2 + line3 + line4 + line5
# For loop to count the lines in the input.txt file opened above
for line in input_file:
val = float(line)
count += 1
total += val
input_file.close()
# Assigning a variable to the calculation of average from the for loop above
total_avg = total / count
# Printing that average total to the screen
print(f'{total_avg:.1f}')
# Designating output file to write to
output_file = open('/home/ed/files/Documents/School/Classes/ITEC2270-01_Application_Development/output.txt', 'w')
# Write the sum total of the input file to the output file
output_file.write(f'Sum: {total_sum}n')
#output_file.write(f'Average: {total_avg}n')
if __name__ == '__main__':
main()
Yet, when I write just the for loop for the average in a separate script I get the results I am looking for without error:
def main():
total = 0.0
count = 0
input_file = open(r'/home/ed/files/Documents/School/Classes/ITEC2270-01_Application_Development/input.txt', 'r')
for line in input_file:
val = float(line)
count += 1
total += val
input_file.close()
total_avg = total / count
print(f'The average of all numbers in the file is {total_avg:.1f}.')
main()
What am I doing wrong in the original script?
The output result I am expecting to the screen (and eventually to a file) is 21.0