读取特定输入python的文件

读取特定输入python的文件,python,python-3.x,Python,Python 3.x,因此,我正在编写一个代码来登录并创建用户名和密码,在登录时,我正在读取一个外部文件,其中包含字典形式的所有用户名和密码,例如{“aaaaaaaa”:“aaaaaa999”} 这是读取它的代码 f3 = open("helloworld.txt","r") user = input("Enter login name: ") if user in f3.read(): passw = input("Enter password: ") print("") if user in

因此,我正在编写一个代码来登录并创建用户名和密码,在登录时,我正在读取一个外部文件,其中包含字典形式的所有用户名和密码,例如{“aaaaaaaa”:“aaaaaa999”}

这是读取它的代码

f3 = open("helloworld.txt","r")
user = input("Enter login name: ")

if user in f3.read():
   passw = input("Enter password: ")
   print("")

   if user in f3.read() and passw in f3.read():
        print ("Login successful!\n")


   else:
        print("")
        print("User doesn't exist!\n")
f3.close()
但是,当我尝试阅读它时,它总是说用户不存在,任何建议函数
f3.read()
会立即读取整个文件,并将文件指针移到末尾。未关闭并重新打开文件而读取的任何后续文件将返回
None

您需要将文件解析到一个数据结构中,该结构允许您搜索包含,而不是检查整个文件中是否存在名称或密码。如果两个用户拥有相同的密码,会发生什么情况?如果只是在整个文件中搜索单个字符串,则无法确保给定用户名的密码是正确的

例如,假设您的文件如下所示:

username1,password1
username2,password2
username3,password3
import ast
# since you're storing the credentials in a dict format
# ast.literal_eval can be used to parse the str to dict
creds = ast.literal_eval(f3.read())
if user in creds and creds[user] == passw:
    #login success 
您的解析代码应该打开并读取文件,并在每次不搜索整个文件的情况下检查是否包含:

users = {}

with open("helloworld.txt") as f3:
    for line in f3:
        name, password = line.split(",")
        users[name] = password.strip()

user = input("Enter login name: ")

if user in users:
    passw = input("Enter password: ")
    print()

    if passw == users[user]:
        print("Login successful!")

    else:
        print("Bad password")

else:
    print("Bad username")
请注意,我已将您的文件打开更改为使用(关键字
with
)。您应该这样做,以实现更可靠的资源管理。您还可以通过使字典生成成为a,并可能通过使用异常来处理字典检查,而不是
(如果X在Y中)

with open("helloworld.txt") as f3:
    pairs = (line.split(",") for line in f3)
    users = {name:password.strip() for name, password in pairs}

user = input("Enter login name: ")
passw = input("Enter password: ")

try:
    if passw == users[user]:
        print("Login successful!")
    else:
        print("Bad password")
except KeyError:
    print("Bad username")

您甚至可以将用户/密码词典的创建浓缩到一个单一的理解中,但我认为这会极大地妨碍可读性,而没有任何好处。

出现问题的原因是:

if user in f3.read() and passw in f3.read():
当您第一次使用
f3.read()
时,它会将指针移到末尾,如果不重新打开,您将无法再次读取它

因此,您可以在第一次读取文件时读取并解析它,如下所示:

username1,password1
username2,password2
username3,password3
import ast
# since you're storing the credentials in a dict format
# ast.literal_eval can be used to parse the str to dict
creds = ast.literal_eval(f3.read())
if user in creds and creds[user] == passw:
    #login success 
在不重新打开文件内容的情况下重新读取文件内容的另一种方法是在调用
f3.read()
之前调用
f3.seek(0)
。这将移动指针以重新开始,但上述操作更适合您的情况。

在将数据读写到文件时,最好使用“with”语句,如下所示:

with open("helloworld.txt","r") as f3:
    # Read user data
    user_data = f3.read()

    # Verify username and password are right

with语句提供更好的异常处理,并自动关闭文件并执行任何必要的清理只在你第一次这样做的时候工作。如果你用字典形式保存所有用户名和密码,你可以考虑将它保存为JSON文件,并将其加载到字典中,这样你就可以加载文件并检查用户名是否存在,如果是的话,如果密码正确的话。