首页 > 解决方案 > 如何将数据保存到 .txt 文件中而不是创建新文件(Python)

问题描述

我正在做一个测验,我已经制作了这个简单的登录系统。它工作得很好,但我有一个小问题。问题是每当有人创建一个新帐户时,它都会创建一个新的 .txt 文件,并且不会将其写入 usernames.txt 文件。谁能帮我解决这个问题?(这是下面的代码)

welcome = input("Do you have an acount? y/n: ") # asks the user if they have a account
if welcome == "n":
    while True:
        username  = input("Enter a username: ")
        password  = input("Enter a password: ")
        password1 = input("Confirm password: ")
        if password == password1:
            file = open(username+".txt", "w")
            file.write(username+":"+password)
            file.close()
            #saved the username and password so that they can Login in.
            welcome = "y"
            break
        print("Passwords do NOT match!")

if welcome == "y":
    while True:
        login1 = input("Login: ")
        login2 = input("Password: ")
        file = open(login1+".txt", "r")
        data   = file.readline() #reads the file if the account exists
        file.close()
        if data == login1+":"+login2:
            print("Welcome") #if matches then they can start the quiz
            break
        print("Incorrect username or password.")```

标签: pythonpython-3.x

解决方案


正如文档所述,您需要在函数中使用标志a,用于附加模式。open见下文:

$ echo "user_1" > usernames.txt
$ cat usernames.txt 
user_1
$ python
>>> with open('usernames.txt', 'a') as file:
...     file.write('user_2\n')
... 
7
>>> 
$ cat usernames.txt 
user_1
user_2

这样,您只需open将第一条if语句中的函数更改为open('filename.txt', 'a'). 请记住在写入文件时添加换行符。或者名称将放在同一行。

但是,您可能需要检查您的代码。正如@MotKohn 指出的那样,您正在创建一个以用户命名的新文件。也许这不是您所期望的行为。


推荐阅读