2014-12-08 128 views
0

我的代碼有問題,它始終有錯誤'file' object has no attribute '__getitem__'。這裏是我的代碼:'文件'對象沒有任何屬性'__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,但它仍然會返回相同的錯誤。請幫助,並感謝您迴應!

+0

我的你的標識符很短。我建議不要在任何地方使用一個字母的變量名稱,但這更適合編程實踐。 – 2014-12-08 02:29:00

+0

順便說一句,作爲一般規則,你不應該在函數內部有'import'語句,如果你打算多次調用該函數,_especially_。另外,在Python中,你不需要圍繞條件表達式使用括​​號,例如'while(g!= p):'可以更清晰地寫爲'g!= p:' – 2014-12-08 05:34:55

回答

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刪除任何尾隨的換行符。

相關問題