1

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

Community
  • 1
  • 1

3 Answers3

1

You are adding a string to an integer. Try the following when adding the numbers:

s = s + int(i)
Mamoon Raja
  • 487
  • 3
  • 8
0

The strings that you identify as numbers with the str.isnumeric method are still strings. You should convert these strings to integers before performing numeric operations with them.

Change:

s=s+i

to:

s=s+int(i)
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

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.

Yogesh Yadav
  • 4,557
  • 6
  • 34
  • 40