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
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
The issue
I keep getting an error that says:
totalstxt was expected to be lines long, but it was lines long. However, if I remove the
new line I get that I
get this error
totalstxt was expected to be lines long, but it was lines long.
Please review my code & Advise
My code
# Variables initialized
totals
currentsum
# Open the units.txt file for reading
with openunitstxtr as unitsfile:
# Read each line in the units.txt file
for line in unitsfile:
line line.strip
if line :
line line.strip
totals.appendtotals
currentsum
else:
currentsum intline
if currentsum :
totals.appendtotals
# Open the totals.txt file for writing
with opentotalstxtw as totalsfile:
for total in totals:
totalsfile.writestrtotal
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
