“file”对象没有属性“getitem”

2024-04-26 12:44:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码有问题,它总是有错误'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,但它仍然返回相同的错误。请帮忙,谢谢你的回复!


Tags: 代码importtimedef错误randomstartprint
1条回答
网友
1楼 · 发布于 2024-04-26 12:44:24

作为错误消息状态,文件对象没有__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和正在每一行上调用^{},以删除任何后面的换行符。

相关问题 更多 >