preposity
preposity

Reputation: 21

How do I add these numbers from a text file together?

I have a file of numbers that are organized in different lines.

I've been working on this since 8 this morning and I keep running into the same two problems:

  1. when I try to split the file by line, I can't do any math because it's a list
  2. when I don't split them up, nothing can happen because there is '\n' all over the file because there are multiple lines.

The file looks like this:

6 7 3 7 35 677
202 394 23 

595 2 30 9
39 3 5 1 99

I basically want to add up all the numbers per line. So I want to add 6,7,3,7,35,677 together and so on. But the lines in the two "paragraphs" need to stay together.

This makes the most sense to me but it doesn't work.

filename = input('Enter filename: ')
f = open(filename, 'r')
data = f.read().split()
my = (int(data[0]))
text = (int(data[1]))
sum(my,text)

I have no idea what's going on. I know i need to split('\n') but then I can't do any math. I can't convert to int either. Any advice?

Upvotes: 1

Views: 127

Answers (5)

Steven Summers
Steven Summers

Reputation: 5394

This will do what you want

filename = input('Enter filename: ')
with open(filename, "r") as file:
    for line in file:
        if line.strip():
            total = sum(int(i) for i in line.split())
            print(total)
        else:
            print() # print new line if line is empty
#Output
735
619
636
147

Upvotes: 0

ChrisD
ChrisD

Reputation: 3518

Something along these lines might help.

filename = input('Enter filename: ')

with open(filename) as f:
    for line in f:
        # split line into a list of numbers (as strings)
        line = line.split()

        if not line:
            # If the line is empty, print a blank line
            print()
        else:
            # otherwise get the total for the line
            total = 0
            for n in line:
                total += int(n)

            print(total)

Upvotes: 0

Eli Korvigo
Eli Korvigo

Reputation: 10513

from itertools import imap


with open("your_file") as inp:
    for numbers in (imap(int, line.strip().split()) for line in inp):
            print(sum(numbers)) if numbers else print()

If you're on Python 3, remove the import line and replace imap with map

Upvotes: 0

Mangu Singh Rajpurohit
Mangu Singh Rajpurohit

Reputation: 11420

with open("file.txt", "r") as objFile:
    lsNos = objFile.readLines()

total = 0
for strLine in lsNos:
   if strLine.strip():
      lsNos = strLine.split(" ")
      for No in lsNos:
        if No.strip():
          total += int(No.strip())

Upvotes: 1

pygeek
pygeek

Reputation: 7404

Once you split, you need to convert the "text" type str or Unicode to integer, float, or decimal.

Upvotes: 0

Related Questions