python - 再次运行程序时,文本文件会自行清除
问题描述
我制作了一个允许用户创建帐户的程序。在我尝试登录功能之前它似乎有效,它一直提醒我用户名和密码不存在。当我重新运行程序并创建一个帐户时,txt 文件里面有我的名字和密码。但是,当我关闭程序并重新打开它以运行登录功能时,名称和密码不再存在。有想法该怎么解决这个吗?
PS:我对这一切都很陌生,如果有什么我可以/应该做的,请告诉我。
while True:
#Account file and same file as list.
AccountsFile = open("AccountProj.txt", "w+")
AccountList = [line.split(',') for line in AccountsFile.readlines()]
#Creates an account
def createaccount():
while True:
newname = (input("Please create a username: "))
if newname in AccountsFile:
print("Username already in use.")
continue
elif newname not in AccountsFile:
newpassword = input("Please create a password: ")
checkpassword = input("Re-enter password: ")
if checkpassword == newpassword:
print("Account Sucessesfuly created!")
AccountsFile.write(newname + "\n")
AccountsFile.write(checkpassword + "\n")
AccountsFile.close()
break
elif checkpassword != newpassword:
print("Passwords do not match")
continue
#Logs into an account
def loginaccount():
while True:
username_entry = input("Enter username: ")
if username_entry not in AccountList:
print("Username not found. Please enter a valid name")
continue
elif username_entry in AccountList:
password_entry = input("Enter password: ")
if password_entry in AccountList[AccountList.index(username_entry) + 1]:
print("Login sucessful!")
AccountsFile.close()
break
if password_entry not in AccountList[AccountList.index(username_entry) + 1]:
print("Username and password do not match. Please try again.")
AccountsFile.close()
continue
#Asks if user wants to create or login to an account
loginchoice = input("Would you like to login? (Y/N) ")
if loginchoice in ('Y', 'N'):
if loginchoice == 'Y':
loginaccount()
if loginchoice == 'N':
createchoice = str(input("Would you like to create an account? (Y/N) "))
if createchoice in ('Y', 'N'):
if createchoice == 'Y':
createaccount()
if createchoice == 'N':
exit()
break
else:
print("Invalid Input")
解决方案
您以w+
模式打开文件,这将覆盖您以前的内容,因为它从文件的开头开始写入。
相反,您应该使用将文本附加到任何先前编写的内容的a
模式。
请参阅:https ://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files :
(...) 模式可以是 'r' 表示只读取文件,'w' 表示只写入(同名的现有文件将被删除),'a' 打开文件以进行追加;写入文件的任何数据都会自动添加到末尾。
推荐阅读
- javascript - 跨屏幕共享通用导航选项
- python - Tensorflow(Python):如何将标量附加到张量中的每一行
- sql-server - 如何自定义ApplicationUser的Id字段
- javascript - 实现数据表按钮的问题(HTML5 导出)
- windows - 将日志数据转换为所需格式的 csv 文件
- android - 当密钥库或属性不存在时,Android 签名应用程序回退
- javascript - 使用锚标签链接打开标签?
- javascript - 如何使用 Javascript 使网页始终保持最新状态?
- ios - Sinch 快速音频和视频通话文档或教程
- node.js - 我如何知道在 findOneAndUpdate 方法中是否返回了新文档?