python不能打开txt文件,Python无法从文本文件正确读取?

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 the text file and compares it with a user input to see if it is present in the text file. For some reason when I input the first email "tom@gmail.com" it reads that from the text file but not "Password1", however it reads "harry@gmail.com" correctly as well as "Password2" correctly. I cant find any way to get around this and fix this? No error is received so I'm not sure where its going wrong. Here is my code:

def Login():

with open("logindata.txt","r") as file:

for line in file:

line=line.split(",")

logindata.append([line[0],line[1].rstrip()])

print(logindata)

found=False

while found == False:

email=input("Enter email:")

password=input("Enter password:")

with open("logindata.txt","r")as file:

for line in file:

line = line.split(",")

if email in line:

print("Correct email")

if password in line:

print("Correct Password")

found=True

if __name__ == "__main__":

Login()

if the code is run and you try the inputs I gave at the start then only the second email and password combination works. Here is what the text file looks like text file format

Appending:

username=input("Enter a new email")

password=input("Enter a password")

with open('logindata.txt','a')as file:

line='\n'+ username + ',' + password

file.write(line)

print("user added")

解决方案

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

with open("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")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值