python - 如何将数据保存到 .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.")```
解决方案
正如文档所述,您需要在函数中使用标志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 指出的那样,您正在创建一个以用户命名的新文件。也许这不是您所期望的行为。
推荐阅读
- mule - 在 DataWeave 中映射嵌套地图时出现问题
- go - 如何附加到二维切片
- jquery - 如何将原始选择框的名称传递给 selectize.js 加载方法?
- c# - 需要将 XML 内容添加到 HttpResponseMessage C# 的正文中
- php - Laravel 5.6,电子邮件未使用 sendmail 驱动程序在服务器上发送
- php - 如何使用存储在数据库中并在新页面中回显的 PHP 代码?
- java - 使用 apache camel 读写 excel 文档
- mysql - SQL 查询,带有 NULL 的 LEFT JOIN
- php - 如何测试仅使用 PHPUnit 调用模拟的特定方法
- java - 字符串缓冲区线程安全