i我正在尝试python中的文件读数,它只是在我尝试添加一些东西

问题描述 投票:0回答:1

这里是代码

login = open("login.txt", "a+")
passw = open("passw.txt", "a+")

state = 0
print("What do you want to do?")
print("1. Log in")
print("2. Register")
dec = int(input())
if dec == 1:
    print("Enter your login:")
    log = input()
    print("Enter your password:")
    pas = input()
    if log == login.read() and pas == passw.read():
        print("You are logged in")
        state = 1
        login.close()
        passw.close()
    else:
        print("Incorrect login or password")
        state = 0
        login.close()
        passw.close()

elif dec == 2:
    print("Enter your login:")
    log = input()
    print("Enter your password:")
    pas = input()
    login.write(log)
    passw.write(pas)
    print("You are registered")
    state = 1
    login.close()
    passw.close()

if state == 1:
    print("What do you want to do?")
    print("1. Read the file")
    print("2. Write to the file")
    print("3. Log out")
    dec = int(input())
    if dec == 1:
        file = open("supasceret.txt", "r")
        print(file.read())
        file.close()
    elif dec == 2:
        file = open("supasecret.txt", "a+")
        print("Enter the text:")
        text = input()
        file.write(text)
        file.close()
    elif dec == 3:
        state = 0
        print("You are logged out")

当我尝试在第41-42行之间添加另一个功能时,它突然停止工作,即使重新恢复代码并运行它仍然无法正常工作,现在它不断地说“不正确的登录或密码”。我什至清除了文件,然后从他开始注册了相同的结果

我正在登录,并希望收到“您已登录”

python
1个回答
0
投票
以+模式打开文件,您应该使用R+模式正确处理读写和写作。在执行读取操作之前,请使用Seek(0)将文件指针重置为开始;否则,read()可以返回一个空值。比较读取数据时,请使用.strip()删除不必要的空间。此外,在注册过程中,在撰写新条目之前使用truncate()清除文件内容将阻止旧数据持续存在。这些更改将确保登录和注册功能正常工作而没有错误。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.