Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'str' object is not callable in Python [duplicate]

I have written following program for my project purpose.

import glob
import os
path = "/home/madhusudan/1/*.txt"
files = glob.glob(path)

s1 = "<add>\n<doc>\n\t<field name = \"id\">"
s2 = "</field>\n"
s3 = "<field name = \"features\">"
s4 = "</doc>\n</add>"

i = 150
for file in files:
    f = open(file,"r")
    str = f.read()
    file1 = "/home/madhusudan/2/"+os.path.splitext(os.path.basename(file))[0] + ".xml"
    f1 = open(file1,"w")
    content = s1 + str(i) + s2 + s3 + f.read() + s2 + s4 
    f1.write(content)
    i = i + 1

While running this code I am getting following error:

Traceback (most recent call last):
  File "test.py", line 18, in <module>
    id1 = str(i)
TypeError: 'str' object is not callable

Can anyone help me to solve this?

like image 456
Madhusudan Avatar asked Nov 28 '25 16:11

Madhusudan


2 Answers

You assigned the file contents to str:

str = f.read()

This masks the built-in function.

Don't use str as a local name; pick something else.

like image 188
Martijn Pieters Avatar answered Dec 01 '25 04:12

Martijn Pieters


In the following line, the code overwrite builtin function str with a string object.

str = f.read()

Use different name to prevent that.


>>> str(1)
'1'
>>> str = 'string object'
>>> str(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
like image 33
falsetru Avatar answered Dec 01 '25 05:12

falsetru