Skip to main content
 首页 » 编程设计

Python 索引错误 : list assignment index out of range when listing txt file

2025年04月02日15zhenyulu

所以,我得到了这个错误

    Traceback (most recent call last): 
     File **, line 15, in <module> 
        del a[del_line] 
    IndexError: list assignment index out of range 

我正在尝试制作一个程序来生成密码组合,但在另一个程序测试它们时几乎立即删除它们,我似乎无法获得正确的代码... 这是我的编码 -

    from __future__ import print_function 
    import itertools 
    import sys 
    from time import sleep  
 
    del_line = -1 
    f1 = open("passfile.txt", "w") 
    res = itertools.product("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", repeat=8) 
    for i in res: 
       print(''.join(i), file=f1) 
       sleep(.5) 
       del_line += 1 
       with open("passfile.txt","r") as textobj: 
           a = list(textobj) 
       del a[del_line] 
       with open("textfile.txt","w") as textobj: 
            for n in a: 
                textobj.write(n) 

哦,顺便说一句,我正在运行 python 2.7.11

请您参考如下方法:

更新:

from __future__ import print_function 
import itertools 
import sys 
from time import sleep  
 
f1 = open("passfile.txt", "w") 
res = itertools.product("ABCD", repeat=2) 
for i in res: 
    text = "" 
    for string in i: # makes the iterated i 'readable', i is a list with each letter as seperate entry, can be removed 
        text += string 
    print(text, file=f1) 
    f1.flush() 
    #sleep(.5) 
    f2 = open("passfile.txt", "r") 
    a = list(f2)[:-1] 
    with open("textfile.txt","w") as textobj: 
        for n in a: 
            textobj.write(n) 

根据您希望将 i 的结果存储为列表还是字符串,您应该使用 AndreyT 的代码或我的代码。技巧本身确实在 f1.flush() 中。可以在这个答案中找到更多信息: what exactly the python's file.flush() is doing?