# Add value in the last of each row in python

i am new in python. i try to add the integer in the end of each row and save that values in new file. here is current code.

```
file = open("Task1.txt","r")
f1 = open("out.txt", "w+")
for line in file:
if not line.lstrip().startswith('#'):
for l in line.split():
a = l[0]
b = l[-1]
l1= a + b
s = sum(int(num) for num in l1)
for line1 in line:
f1.write(line1)
```

### 1 Answer

In the code above, you need to first ensure that l[0] and l[1] are not strings as the "l1 = a + b" line will just concatenate them.

If these are expected to be numbers, you can use: a, b = int(l[0]), int(l[1])

or better: s = int(l[0]) + int(l[1])

Currently, s = sum(int(num) for num in l1) will add up the digits in l1 and will fail if one of the characters is a letter. For instance: if a = '12' and b = '34', l1 will equal '1234', and s will equal '10'. if a = '12' and b = '34a', l1 will equal '1234a', and sum(int(num) for num in l1) will fail as you are trying to make the last character 'a' into an integer.

user12346170
posted this

## Have an answer?

JD

Welcome to SO! Please include

`Task1.txt`

or hardcode it in assuming it's being read OK. Thanks.