Search code examples
pythonfiletypeerrormagic-methods

'file' object has no attribute '__getitem__'


I am having a problem with my code where it always has the error 'file' object has no attribute '__getitem__'. Here is my code:

def passHack():
    import random
    p1 = random.choice(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"])
    p2 = random.choice(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"])
    p3 = random.choice(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"])
    p4 = random.choice(["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"])
    p = (p1 + p2 + p3 + p4)
    g = 0000
    a = 0
    import time
    start_time = time.time()
    print "Working..."
    while (g != p):
        a += 1
        f = open('llll.txt')
        g = f[a]
        print g
        f.close()
    if (g == p):
        print "Success!"
        print "Password:"
        print g
        print "Time:"
        print("%s seconds" % (time.time() - start_time))

def loopPassHack():
    t = 0
    while (t <= 9):
        passHack()
        t += 1
        print "\n"

passHack()

I noticed that this happened when I added g = f[a], but I tried adding the attribute __getitem__ to g, f, and a, but it still returns the same error. Please help, and thanks if you respond!


Solution

  • As the error message states, file objects do not have a __getitem__ special method. This means that you cannot index them like a list because __getitem__ is the method which handles this operation.

    However, you could always read the file into a list before you enter the while-loop:

    with open('llll.txt') as f:
        fdata = [line.rstrip() for line in f]
    while (g != p):
       ...
    

    Then, you can index the list of lines as you were:

    a += 1
    g = fdata[a]
    print g
    

    As an added bonus, we are no longer opening and closing the file with every iteration of the loop. Instead, it is opened once before the loop starts and then closed as soon as the code block underneath the with-statement is exited.

    Also, the list comprehension and is calling str.rstrip on each line to remove any trailing newlines.