'file'对象没有属性'__getitem__'

时间:2014-12-08 02:27:06

标签: python file typeerror magic-methods

我的代码存在问题,因为它始终存在错误'file' object has no attribute '__getitem__'。这是我的代码:

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()

我注意到这是在我添加g = f[a]时发生的,但我尝试将属性__getitem__添加到gfa,但它仍然返回相同的错误。请帮忙,谢谢你的回复!

1 个答案:

答案 0 :(得分:4)

如错误消息所述,文件对象没有__getitem__特殊方法。这意味着您不能像列表一样索引它们,因为__getitem__是处理此操作的方法。

但是,在输入while循环之前,您始终可以将文件读入列表:

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

然后,您可以按原样索引行列表:

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

作为额外的奖励,我们不再在循环的每次迭代中打开和关闭文件。相反,它在循环开始之前打开一次,然后在with-statement下面的代码块退出后立即关闭。

此外,list comprehension并在每一行上调用str.rstrip以删除任何尾随换行符。