lapots
lapots

Reputation: 13415

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

I've got simple python functions.

def readMainTemplate(templateFile):
    template = open(templateFile, 'r')
    data = template.read()
    index1 = data.index['['] #originally I passed it into data[]
    index2 = data.index[']']
    template.close()
    return data[index1:index2]

def writeMainTemplate(template, name):
    file = open(name, 'w')
    file.write(template)
    file.close()

#runMainTemplate('main.template')
def runMainTemplate(template):
    code = readMainTemplate(template)
    writeMainTemplate(code, 'main.cpp')

They basically suppose to read from file some kind of template(something like this)

--template "main"
[
        #include <iostream>

        using namespace std;

        int main()
        {
            return 0;
        }
]

and then write it to file(basically generating main.cpp template)

I run it from command line using this command

python -c "from genmain import runMainTemplate; runMainTemplate('main.template')"

but I've got this error

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "genmain.py", line 18, in runMainTemplate
    code = readMainTemplate(template)
  File "genmain.py", line 6, in readMainTemplate
    index1 = data.index['['] #originally I passed it into data[]
TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

I thought that data = template.read() supposed to return string and string should allow to perform operation slicing [:].

But why there is an error?

Also a question: where I should put python scripts in order to run it anywhere in filesystem?(I want to generate file anywhere in the filesystem in the current folder by providing path to the template)

Upvotes: 7

Views: 51532

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599946

The problem is that index is a method and needs to be called with () not []. To use Kasra's example:

>>> s="aeer"
>>> s.index('a')
0

Upvotes: 25

Related Questions