gpt4 book ai didi

python - 让python写入文件中的新行

转载 作者:太空宇宙 更新时间:2023-11-04 11:10:43 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的登录系统,因为我很无聊并且想学习 python,我正在尝试将用户名存储在一个文件中,但新用户名只是替换列表中的当前用户名。

#USENRAME UNENCRYPTED PASSWORD SYS

print ("WOuld you like to login or signup (login/signup)")
choice = input()

if choice == "signup":
print ("Can you enter your username please?")
username = input()
with open('username') as f:

if username in f.read():
print("That Username already exists")

else:

f= open("username","w+")
f.write(username + "\n")
f.close()

如果我输入的第一个用户名是“Dave”然后关闭程序,我注册的下一个用户名是“Harry”“Harry”将替换“用户名”第一行中的“Dave”文件。

最佳答案

你不需要打开你的文件两次,但是当你第一次打开它时,你希望能够做的是追加到已经存在的内容上。

with open('username.txt','a+') as f:
if username in f.read():
print("That Username already exists")
else:
f.write(username + "\n")


如果您不确定,请尝试阅读此内容。

https://www.guru99.com/reading-and-writing-files-in-python.html

关于python - 让python写入文件中的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58285515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com