Question: Goal: Learn to read structured files line by line. Assignment: A file named units.txt records the contents of the containers in a logistic hub. Each

Goal: Learn to read structured files line by line.
Assignment: A file named units.txt records the contents of the containers in a logistic hub. Each line contains the number of items, and each container section is separated from the next by a line with a dash. The following is an example file:
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
**** The issue ***
I keep getting an error that says:
`totals.txt` was expected to be 3 lines long, but it was 4 lines long. However, if I remove the
(new line) I get that I
get this error
`totals.txt` was expected to be 2 lines long, but it was 3 lines long.
Please review my code & Advise
** My code **
# Variables initialized
totals =[]
current_sum =0
# Open the units.txt file for reading
with open('units.txt','r') as units_file:
# Read each line in the units.txt file
for line in units_file:
line = line.strip()
if line =="-":
line = line.strip('-')
totals.append(totals)
current_sum =0
else:
current_sum += int(line)
if current_sum >0:
totals.append(totals)
# Open the totals.txt file for writing
with open('totals.txt','w') as totals_file:
for total in totals:
totals_file.write(str(total)+'
')

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!