user10333134
user10333134

Reputation:

How do i calculate sum of rows from text file?

Im new to programming and i needed help with one of my assignments. (not asking for a solution). Im confused how to approach this problem. If you can provide pseudocode to get me in the right direction it be helpful.

So far,

  1. Take an input for a file
  2. Read Files testFile = inputFile.read()
  3. This is where i'm confused. I know there needs to be a for loop to go through the text file. calculate sum for line in testFile: //Logic

Refer to Text File for text file and corresponding expected output.

So for example: without using lens function

x = input("enter a file to read: ") y = input("enter a file to write: ")

filereading = x.readline()

what characters do i need to strip in order to get the two values to add. Also i need the output to have $ # with a space in between.

for line in filereading: \logic

Upvotes: 2

Views: 972

Answers (1)

vash_the_stampede
vash_the_stampede

Reputation: 4606

Pseudocode

open file as test_file

read test_file into something
split something to make list out of something 

loop through something 
    remove $ from all items in something

open other_file to write to

create loop to sum 2 consecutive items in something
    create variable to hold total of two items
    write output statement to other_file

Tried to write out an idea how I handled it in words to help guide you, below is the answer, again not for you to skip to but to use as a guide if you get stuck .

...

...

...

...

SPOILER: Solution

test_file = open('money.txt', 'r')

content = test_file.read()
content = content.split()

for i in range(len(content)):
    content[i] = content[i].strip('$')

other_file = open('print.txt', 'w')

for i in range(0, len(content), 2):
    total = float(content[i]) + float(content[i+1])
    other_file.write(f"${content[i]} + ${content[i+1]} = ${total}\n")

test_file.close()
other_file.close()

Additional

with open(other_file, 'w') as f_obj:
    total = float(content[0]) + float(content[1])
    f_obj.write("$ " + content[0] + " $ " + content[1] + " $ " + 
        str(total) + "\n")
    total = float(content[2]) + float(content[3])
    f_obj.write("$ " + content[2] + " $ " + content[3] + " $ " + 
        str(total) + "\n")
    total = float(content[4]) + float(content[5])
    f_obj.write("$ " + content[4] + " $ " + content[5] + " $ " + 
        str(total) + "\n")

Here is an example on how to manually enter each statement, also note if you use with open like in this example, the file should close after the with open code is completed

Upvotes: 1

Related Questions