0

Hi i have been given a task to read these numbers from within a text file "1,3,5,7,9,11,13,15," and to add them together how would i do this? So far i have:

file = open("C:\\Users\\Dylan\\Python\\OddNumbersAns.txt", "r")
line = file.read()
intline = int(line)
print(intline)

But i recieve this error:

Traceback (most recent call last):
  File "C:\Users\Dylan\Python\text file add.py", line 3, in <module>
    intline = int(line)
ValueError: invalid literal for int() with base 10: '1, 3, 5, 7, 9, 11, 13, 15, '

Thanks

Answer:

file = open("C:\\Users\\Dylan\\Python\\OddNumbersAns.txt", "r")

line = file.read()

line.split(",")

print (line.split(","))

total = sum([int(num) for num in line.split(',')])

print(total)
2
  • 3
    You're trying to turn the entire line into a single integer. You need to split it up into separate strings first, going by the commas. Investigate the split function. Commented Jan 26, 2014 at 16:40
  • Is your name Dylan by any chance? Commented Jan 26, 2014 at 17:00

3 Answers 3

2

You want the sum() function, after splitting the line on every comma:

total = sum(int(num) for num in line.split(','))

Don't try to call int(line), as that's trying to turn the whole line into a single int.

Instead, you split the line on every comma, yielding a sequence of strings, each of which is cast to int. Putting the whole thing in the sum function adds them together.

Sign up to request clarification or add additional context in comments.

3 Comments

Don't need to make the list, you can call sum like this: total = sum(int(num) for num in line.split(',')). Probably will increases a little in performance. +1 for using sum.
total = sum(map(int, line.split(',')). Even if BDFL doesn't like it, it looks more concise and clear to me.
@PauloBu - you're right, of course. The inclusion of the list was redundant here; I've removed it.
0

If your file contains trailing new line or comma:

#a.txt
1, 3, 5, 7, 9, 11, 13, 15, 
2, 3, 45, 6,

you need to strip it first, then split:

In [174]: with open('a.x', 'r') as f:
     ...:     line=f.read()
     ...:     total=sum(map(int, line.strip(', \n').split(',')))
     ...:     print total
#output: 120

without strip, e.g. '1,2,\n' would be splitted into ['1', '2', '\n'], and int('\n') or int('') would raise a ValueError.

Comments

0

This is the basic stuff you need

>>> txt_line = "1, 2, 3, 4, 5, 6, 7, 8"
>>> 
>>> [int(ele.strip()) for ele in txt_line.split(",")]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> sum([int(ele.strip()) for ele in txt_line.split(",")])
36
>>> 

In addition to this you may have to take care of the file inputs It could either be complete file content or line by line read So I would recommend the following

with open('input_file.txt', 'r') as fp:
    line = fp.readline()
    while line:
        ## Here insert the above logic
        line = fp.readline()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.