3

How do I calculate the sum of numbers from a .txt file?

Data in file is formatted as:

7
8
14
18
16
8
23
...

I read the data from the file and assign every line value to 'line' vatiable, but I want to get something like: result = 7+8+14+...

f = open('data.txt', 'r')   #LOOP AND READ DATA FROM THE FILE
    for line in f:
        code
coredumped0x
  • 768
  • 1
  • 12
  • 28

7 Answers7

6

This is most compact code I can think of right now: (updated to handle the n at the end, thanks, @JonClements!)

with open('file.txt', 'r') as fin:
    ans = sum(int(line) for line in fin if line.strip().isnumeric())

For the code structure you have, you can also go for this:

f = open('data.txt', 'r')
ans = 0
for line in f:
    try:
        ans += int(line.strip())
    except ValueError:
        pass

Edit: Since the confusion with the 'n' has been cleared, the first example can be as simple as

with open('file.txt', 'r') as fin:
    ans = sum(int(line) for line in fin)

Or even this one-liner:

ans = sum(int(line) for line in open('file.txt', 'r'))

But there are certain risks with file handling, so not strongly recommended.

AChampion
  • 29,683
  • 4
  • 59
  • 75
Sufian Latif
  • 13,086
  • 3
  • 33
  • 70
  • 1
    What happens with the `'n'` at the end of the file? (and `for line in fin` is sufficient because `fin` supports an iterable interface. – AChampion Aug 17 '18 at 19:36
  • Didn't notice that! @MurphyAdam Could you please explain? – Sufian Latif Aug 17 '18 at 19:39
  • 1
    @0605002 `.readlines()` will load all lines into memory - you don't need that for this as you can just sum over each line as you go... the other part is that `int('n')` will raise an exception... – Jon Clements Aug 17 '18 at 19:40
  • 2
    You also don't need to .strip as int doesn't take leading/trailing whitespace into account anyway... you might be able to get away with just sum(int(line) for line in fin if line.strip().isdigit()) ( or .isnumeric() depending) – Jon Clements Aug 17 '18 at 19:42
  • @AChampion that's what I said - it does appear that isdigit and isnumeric do though... so it's needed in one place... – Jon Clements Aug 17 '18 at 19:45
  • @0605002 sorry - my bad - you will need to strip in the `if` check else nothing will happen because of the `\n`... – Jon Clements Aug 17 '18 at 19:45
  • 1
    @0605002 regarding your second example... I'd also make it `except ValueError` to catch only the least amount the `pass` statement should deal with... if a keyboard interrupt or an `IOError` occurs... you should let that propagate to something that can handle it instead of swallowing it. – Jon Clements Aug 17 '18 at 19:55
  • Just to note the OP clarified the `n` was just meant to indicate continuation, it looks like it just a list of numbers, so you can simplify back down to `sum(int(line) for line in f)` – AChampion Aug 17 '18 at 19:57
3

Keep it simple:

with open('data.txt', 'r') as f:
    result = sum(map(int, f))

int is mapped over each line from f, then sum() adds up the resulting integers.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • Thank you @Steven Rumbilski. But I get this error and think it's because the file has multiple lines to loop through: with open('data.txt', 'r') as fin: ^ SyntaxError: invalid syntax – coredumped0x Aug 17 '18 at 20:24
  • @MurphyAdam: I forgot a closing parenthesis on my second line. Was that the issue? It won't be because of multiple lines. `sum()` drives the iteration over all the lines (indirectly by iteration over the results of `map()`). – Steven Rumbalski Aug 17 '18 at 20:26
  • Rumbilski Yes, of course! Haven't paid attention to it. Yeah, this is much simpler and works like a charm ^^ Thanks again. – coredumped0x Aug 17 '18 at 20:35
2
file = open("data.txt", "r")
numbers = []

for line in file:
  numbers.append(int(line))

print(sum(numbers))

This basically just creates a list of numbers, where each line is a new entry in the list. Then it shows the sum of the list.

emsimpson92
  • 1,779
  • 1
  • 9
  • 24
2

A simple solution is, it will take care of the \n at the end of each line as well, based on steven's and AChamp's suggestion

with open("abc.txt","r")as f:
    print(sum(int(x) for x in f))
Inder
  • 3,711
  • 9
  • 27
  • 42
1

Here is a solution (consider all of the lines are numbers):

def calculate_number_in_file(file_path):
    with open(file_path, 'r') as f:
        return sum([int(number.strip()) for number in f.readlines()])
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
1

On smartphone...

with open(filepath) as f:
    lines = f.readlines()
numbers = [int(line) for line in lines]
print(sum(numbers))
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
1
with open ('data.txt', 'r') as f:
    data = f.readlines()

sum = 0
for line in data:
    sum += int(line.strip())

print(sum)
Jon Warren
  • 857
  • 6
  • 18
  • No need to read into `data`. Just do it all under your with-statement: `for line in f: ...`. Also no need to `.strip()` as `int()` can handle leading and trailing whitespace. – Steven Rumbalski Aug 17 '18 at 19:48