我渴望建立一个中心。集线器是基于帐户的,因此您需要登录。但我怎么不理解如何将列表保存到文件中。的text.txt:
a = ["tom","password"]
b = ["james","greensky01"]
依旧......但是如何在shell中打开这些列表和/或打印/编辑这些列表。
openFile("text.txt","w")
这是我唯一知道怎么做的事。
那么如何让python 3将用户输入保存到文件中的列表?
答案 0 :(得分:0)
你想要这样的东西吗?
a = ["tom","password"]
b = ["james","greensky01"]
with open("text.txt", "w") as f:
f.write(str((a,b)))
我检查了你的代码,它有一些错误和缩进中不一致的标签和空格的使用,我修改了你的代码在这里工作一个:
a = ["tom","password"]
b = ["james","greensky01"]
login = input("(to login use:\ntom)\n\n>>:")
with open("text.txt", "w") as f:
f.write(str((a,b)))
if login in a or login in b:
pasword= input(">>>:")
if pasword in a and login in a:
print("You are logged in!")
elif pasword in b and login in b:
print("you are logged in!")
else:
print("access failed")
else:
print("failed")
答案 1 :(得分:0)
with open("text.txt","a") as file_:
file_.write(str(a))
file_.write(str(b))
将登录信息放入文件并自动关闭。
然后,如果您想要读取文件并检查用户名和密码是否匹配,请执行以下操作:
with open("text.txt","r") as file_:
for x in file_:
x = eval(x)
if x[0] == "username user enters":
if x[1] == "password user enter":
print("Login Successful")
答案 2 :(得分:0)
这会将用户信息存储到字典中。登录后,字典将作为json转储到文件中。每次程序启动时都会读取json文件。如果json文件不存在,则会生成。
import json
def login(usr):
uN = input("Name: ")
pW = input("Password: ")
if uN in usr.keys():
if pW == usr[uN]:
print("Welcome back.")
else:
print("Incorrect password.")
return False
else:
print("Hello, new person.")
usr[uN] = pW
writeUsers(usr)
return True
def readUsers():
try:
with open("users.json", "r") as f:
return json.load(f)
except FileNotFoundError:
return {}
def writeUsers(usr):
with open("users.json", "w+") as f:
json.dump(usr, f)
users = readUsers()
success = login(users)
while not success:
success = login(users)