Python Not Reading From A Text File Correctly?
I have a code where I have an email and a password in a text file in a list, formatted like this: ['tom@gmail.com','Password1'],['harry@gmail.com','Password2]. My code reads from t
Solution 1:
You are reading text with line separators. Your lines don't look like this:
tom@gmail.com,Password1
They actually look like this:
tom@gmail.com,Password1\n
When splitting that on the comma, you get this:
line = ['tom@gmail.com', 'Password1\n']
and the test 'Password1' in line
fails, but 'Password1\n'
in line would succeed.
The \n
is a newline character. You'd need to remove that first; you could use str.strip()
to handily remove all whitespace from the start and end:
for line in file:
line = line.strip().split(",")
if email in line:
print("Correct email")
if password in line:
print("Correct Password")
Rather than manually split, you can use the csv
module to read your file:
import csv
withopen("logindata.txt", "r") as file:
reader = csv.reader(file)
for user, pw in reader:
if email == user:
print("Correct email")
if password == pw:
print("Correct Password")
Post a Comment for "Python Not Reading From A Text File Correctly?"