Add value in the last of each row in python

942 views python
9

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)

answered question
ggorlen

Welcome to SO! Please include Task1.txt or hardcode it in assuming it's being read OK. Thanks.

furas

maybe use print() to see what you have in variables - it can help to see what code is doing.

furas

you canlcuate some value but never write it . And I don't understand why do you use for line1 in line: f1.write(line1) which probably write line char-by-char - you can write all line directly f1.write(line)

Add a Comment

1 Answer

5

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.

posted this

Please login first before posting an answer.