I'm trying to make a password cracker for a project at school, but I've run into a problem. Here's the code:
dictfile = open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()
Password = "abductors"
for x in DictionaryWords:
if x is Password:
print("Found it!")
else:
print("This password can't be guessed!")
So everytime I run this code, I only get:
"This password can't be guessed!"
However, I made sure the word was in the dictionary I'm using, so I don't understand why the password isn't being guessed. Is there something I'm doing wrong with the code I'm using?
Tonechas
13.8k16 gold badges52 silver badges85 bronze badges
2 Answers 2
You need to change two things with your code: Use == for string comparisons and remove the newline (\n) character by replacing it.
dictfile = open('wordsEn.txt', 'r')
DictionaryWords = dictfile.readlines()
Password = "abductors"
for x in DictionaryWords:
if x.replace("\n", "") == Password:
print("Found it!")
else:
print("This password can't be guessed!")
answered Dec 11, 2016 at 21:26
Niklas Rosencrantz
26.7k78 gold badges247 silver badges448 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Stepwise description of the suggested approach:
- Read the file content using the
read()method instead ofreadlines(). - Generate a list of words using the
split()method. This also removes the newline characters. - Check whether the password is in the dictionary through the
inoperator. This allows you to get rid of theforloop.
This snippet should get the job done:
with open('c:/ScienceFairDictionaryFolder/wordsEn.txt', 'r') as dictfile:
DictionaryWords = dictfile.read().split('\n')
Password = "abductors"
if Password in DictionaryWords:
print("Found it!")
else:
print("This password can't be guessed!")
answered Dec 12, 2016 at 0:28
Tonechas
13.8k16 gold badges52 silver badges85 bronze badges
Comments
lang-py
isfor string comparisons. Use==. 2: You have to remove the line ends:if x.strip('\r\n') == Password:.