Question: FIX THE ERROR, MY CODE IS THERE FOR REFERENCE. Thank you! Contents of units.txt 1 0 1 2 3 9 5 2 8 5 6

FIX THE ERROR, MY CODE IS THERE FOR REFERENCE. Thank you!
Contents of units.txt
10
123
95
285
64
Write some code that creates a file named totals.txt in which each line is the sum of all the item counts per container section. Continuing the above example, the following is the example result:
Contents of totals.txt
228
349
def calculate_totals(input_file, output_file):
totals =[] # List to store total counts for each container section
current_total =0 # Variable to hold the sum for the current section
Step 1: Read the file line by line
with open(input_file, 'r') as file:
for line in file:
line = line.strip() # Remove any leading or trailing whitespace
if line =="-": # If a dash is encountered, save the current total
totals.append(current_total) # Append the sum (even if it's zero)
current_total =0 # Reset the total for the next container section
else:
current_total += int(line) # Add the item count to the current total
Step 2: After finishing, append the last section's total only if it wasn't followed by a dash
if current_total >0: # If there's an unhandled section at the end, add it
| totals.append(current_total)
Step 3: Write the totals to the output file
with open(output_file, 'w') as outfile:
for total in totals:
| outfile.write(f"tal}
") # Write each total on a new line
calculate_totals('units.txt', 'totals.txt')
Feedback
FIX THE ERROR, MY CODE IS THERE FOR REFERENCE.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!