Search code examples
pythonisnumeric

Taking sum of all lines containing number and skipping those with alphabets and write back the sum to another file


I have written the following code which reads a file that contains lines with numbers and alphabets I want to calculate sum of all numbers in a single line and skip the lines with alphabets and finally write back that sum to another file.

File to be read contains data as follows:

a b c d e

1 2 3 4 5

f g h i j

6 7 8 9 10

k l m n o

11 12 13 14 15

My code in python is as follows

 f=open("C:/Users/Mudassir Awan/Desktop/test.txt",'r+')
    s=0
    l=0
    for line in f:
        
       for i in line.split():
           if i.isnumeric():
               s=s+i
       print(s)
       if s!=0:
          m=open("C:/Users/Mudassir Awan/Desktop/jk.txt",'a')
          m.write(str(s))
          m.write("\n")
          
          m.close()
     s=0

The error that I get says"TypeError: unsupported operand type(s) for +: 'int' and 'str'"

enter image description here


Solution

  • isnumeric() only checks if all characters in the string are numeric characters or not. It does not change their data type.

    You need to convert the data type of i which is str after line.split()

    for i in line.split():
               if i.isnumeric():
                   s=s+int(i)
    

    In Python, decimal characters, digits (subscript, superscript), and characters having Unicode numeric value property (fraction, roman numerals) are all considered numeric characters.