Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python readlines() only working with the last line in txt file

Im trying to make a python script that will change a password based on the day of the week, but whenever I use the if function to see if the password I typed matches the password on the file it always comes back as false. I’ve noticed that it only comes back as true when I have it check my typed password to the line of text on the file.

Code:

passwords = open('passwords.txt', "r")
content = passwords.readlines()
userpassword = input()


if userpassword == content[x]:
    print('same')
else:
    print('different')

passwords.txt:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

test1
test2
test3
test4

So when I change x in the content to 0,1 or 2 and input the corresponding password it will always output ‘different’, but if x is changed to 3 and I enter the right password it will output ‘same’. It also doesnt matter how many passwords I have in the txt file, it will only output ‘same’ if I change x to the number that corresponds with the last line in the txt file while also imputing the same password

>Solution :

Carriage return are in every string of your content list (except the last one) and doesn’t allow the match with userpassword.

You could do content = open("passwords.txt",'r').read().splitlines() to remove those \n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading