Reputation: 21
So, I got this error
Traceback (most recent call last):
File **, line 15, in <module>
del a[del_line]
IndexError: list assignment index out of range
I am trying to make a program that will generate password combinations, but delete them almost immediately while another program tests them, I just can't seem to get the right code... Here's my coding -
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)
Oh, I'm running python 2.7.11 btw
Upvotes: 2
Views: 252
Reputation: 1499
Possibly, you should add
f1.flush()
after
print(''.join(i), file=f1)
Explanation: what exactly the python's file.flush() is doing?
(Updated)
from __future__ import print_function
import itertools
import sys
from time import sleep
f1 = open("passfile.txt", "w")
# Note: count of permutations was reduced, because it takes very long time
res = itertools.product("ABCDEF", repeat=2)
for i in res:
print(''.join(i), file=f1)
f1.flush()
with open("passfile.txt","r") as textobj:
a = list(textobj)
del a[-1]
# Warning: textfile.txt will be overwritten each time
with open("textfile.txt","w") as textobj:
for n in a:
textobj.write(n)
Upvotes: 0
Reputation: 35
Updated:
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)
Depending on whether you want the result of i stored as a list or as a string, you should use either AndreyT's code or mine. The trick itself was indeed in f1.flush()
. More info on that can be found in this answer:
what exactly the python's file.flush() is doing?
Upvotes: 1