[Solved] TypeError: ‘builtin_function_or_method’ object has no attribute ‘__getitem__’

I’ve got simple python functions.

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

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

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 "", line 18, in runMainTemplate
    code = readMainTemplate(template)
  File "", 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 = 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)

Enquirer: lapots


Solution #1:

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')
Respondent: Daniel Roseman

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy