I'm having a little issue with my code, mainly (I think) with the try/except part. My code will generate a wordlist of the users choice. Here is the code:
def gen_wordlist():
filename = input("Please enter the name of the wordlist: ")
try:
my_file = open(filename, 'r')
except FileNotFoundError:
retry = input("No file named "+filename+". Would you like to try again (y/n)")
if retry == 'y' or retry == 'Y':
gen_wordlist()
else:
print("Goodbye :-)")
sys.exit()
words = my_file.read()
my_file.close()
return(words.split())
words = gen_wordlist()
If I enter a valid filename on the first attempt, it works as it should. However, if I enter an invalid filename and choose to try again, I get the following error, even if my second attempt is definitely a valid filename:
Traceback (most recent call last):
File "TEST.py", line 20, in <module>
words = gen_wordlist()
File "TEST.py", line 15, in gen_wordlist
words = my_file.read()
UnboundLocalError: local variable 'my_file' referenced before assignment
I can't work out why though. Surely, when I select 'y', the code just executes from the beginning of the gen_wordlist() function, and should work the same as if I had entered a valid filename on the first attempt, right?