Hello,

I have problem with arithmetic in python when use it like this code

#!/usr/bin/python

AA = open("a.txt").readline()
print AA
BB = 100
print BB + AA

Appear to me this error :

Traceback (most recent call last):
File "aa.py", line 6, in ?
print BB + AA
TypeError: unsupported operand type(s) for +: 'int' and 'str'


when delete the arithmetic line "print BB + AA" or change it to "print BB + 50"
the code working good
20

150

Why not confess with number when i get it from file ?
And the same error if I get the number from another python file like modul :

import file
print BB + file.number

any idea ?

Thanks

Recommended Answers

All 4 Replies

The number from file looks like number but it is string until you transform it to real number with int(stringnumber) or float(stringnumber) You can see the information, that operand is wrong type from the error message:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

You can confirm it by replacing your print:

print type(AA),repr(AA)

You can confirm it by replacing your print:
Python Syntax (Toggle Plain Text)

1.
print type(AA),repr(AA)

I did that and still appear that error

Any solution ?

int or float:

open('testfile.txt','w').write(str(1234))
print int(open('testfile.txt').read())+20

yes, thanks alot tonyjv :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.