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
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
def calculatetotalsinputfile, outputfile:
totals # List to store total counts for each container section
currenttotal # Variable to hold the sum for the current section
Step : Read the file line by line
with openinputfile, 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.appendcurrenttotal # Append the sum even if it's zero
currenttotal # Reset the total for the next container section
else:
currenttotal intline # Add the item count to the current total
Step : After finishing, append the last sections total only if it wasn't followed by a dash
if currenttotal : # If there's an unhandled section at the end, add it
totals.appendcurrenttotal
Step : Write the totals to the output file
with openoutputfile, w as outfile:
for total in totals:
outfile.writeftal
# Write each total on a new line
calculatetotalsunitstxt 'totals.txt
Feedback
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
