对于一个项目。 我在文本文件中使用数据库创建了一个登录名。
Username|Password|Name|Year|Gender
这就是它保存在文本文件中的方式。 我需要创建一个检查器,检查用户名是否已被使用。
def menu():
menuAnswer = input("Would you like to login or register? 1 For Login. 2 For Register >> ")
print ("---------------------")
if menuAnswer == "1":
login()
if menuAnswer == "2":
register()
if menuAnswer != "1" or "2":
print ("Invalid Option. Try Again.")
menu()
def register():
global nameInput
nameInput = str(input("What is your first name? >> "))
global yearInput
yearInput = str(input("What year was you born in? >> "))
global passwordInput
passwordInput = str(input("What is your password? >> "))
global genderInput
genderInput = str(input("What is your gender? M/F >> "))
print ("---------------------")
nameForUN = nameInput[:3]
nameForUN = nameForUN.upper()
yearForUN = yearInput[-2:]
global UNToSave
UNToSave = nameForUN + yearForUN
UNToSave = str(UNToSave)
UNChecker()
def saveToFile():
print ("Creating your account")
DB = open("DB.txt", "a")
DB.write("\n" + UNToSave + fileSpacer + passwordInput + fileSpacer + nameInput + fileSpacer + yearInput + fileSpacer + genderInput)
DB.close
DB = open("DB.txt", "a")
DB.write("\n" + UNToSave + fileSpacer + passwordInput + fileSpacer + nameInput + fileSpacer + yearInput + fileSpacer + genderInput)
print ("Account created")
print ("Please write down your username and password as it will not be given back.")
print ("Account details;")
print ("Username >> " + UNToSave)
print ("Password >> " + passwordInput)
DB.close
print ("---------------------")
print ("Returning you to the main menu")
menu()
def UNChecker():
DB = open("DB.txt").read().split("\n")
print (UNToSave)
for i in range(len(DB)): DB[i] = DB[i].split("|")
while True:
for user in DB:
UNToCheck = user[0]
if UNToSave == UNToCheck:
print ("Your username has already been registered.")
print ("Returning you back to the register menu.")
DB.close
register()
return (" ")
print ("Your username is valid")
print ("---------------------")
saveToFile()
def login():
DB = open("DB.txt").read().split("\n")
for i in range(len(DB)): DB[i] = DB[i].split("|")
while True:
UN = str(input("Username >> "))
PW = str(input("Password >> "))
for user in DB:
#Remember it starts at 0.
UNCheck = user[0]
PWCheck = user[1]
if UN == UNCheck and PW == PWCheck:
print("Hello " + user[0] + ".")
print("You are logged in as " + user[2] + ".")
menu()
return (" ")
DB.close
print("Wrong username/password.")
print("Try again!\n\n")
fileSpacer = ("|")
UNToSave = ("Hi")
menu()
然而,它总是给出误报。我需要它来检查是否存在已存在的用户名。 我将UNToSave声明为不同函数中的全局变量。使用
UNToSave = "Jon01"
为什么它永远不会将用户返回到注册菜单并告诉他们用户名已经注册的任何帮助。
的Python(3.5.2)
答案 0 :(得分:0)
读取文件的更简单方法是将其视为带有" |"的CSV文件。作为分隔符。要读取CSV文件,您可以使用csv标准模块。在这里,使用DictReader
将每行作为Python dict
更合适。
这是一个在内存中有文件的例子:
import io
data = """\
Username|Password|Name|Year|Gender
jdoe|S3cret|John DOE|2017|M
jadoe|Secr3t|Jane DOE|2018|F
"""
import csv
with io.StringIO(data) as csvfile:
reader = csv.DictReader(csvfile, delimiter='|')
for row in reader:
print(row['Username'], row['Name'])
打印:
jdoe John DOE
jadoe Jane DOE
因此,要阅读您的文件并获取所有记录,您可以写:
records = []
with io.open("DB.txt", mode="r", encoding="UTF-8") as csvfile:
reader = csv.DictReader(csvfile, delimiter='|')
for row in reader:
records.append(row)
结果是records
:(有序)词典列表。例如:
[OrderedDict([('Username', 'jdoe'),
('Password', 'S3cret'),
('Name', 'John DOE'),
('Year', '2017'),
('Gender', 'M')]),
OrderedDict([('Username', 'jadoe'),
('Password', 'Secr3t'),
('Name', 'Jane DOE'),
('Year', '2018'),
('Gender', 'F')])]
鉴于用户名,您希望在记录中进行搜索。 您可以使用一个简单的循环(因为我们的记录没有编入索引)。
username = "jdoe"
for record in records:
if record["Username"] == username:
print("Found: {0}".format(record))
break
else:
print("Not found!")
注意:我们使用break
在找到循环时停止循环。只有在找不到用户名时才会调用else
语句。
添加用户所需的只是创建一个具有所需值的新dict
。并将此dict
附加到记录 list
:
user = {'Username': "me",
'Password': "0@&foz1p",
'Name': "My NAME",
'Year': "2010", # it's a string
'Gender': "M"}
records.append(user)
要保存用户,您可以使用DictWriter
(类似于DictReader
)。
headers = "Username|Password|Name|Year|Gender".split("|")
with open("DB.txt", mode='w', encoding="UTF-8") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=headers)
writer.writeheader()
for record in records:
writer.writerow(record)
现在,是时候阅读文档了。然后,您可以创建一些函数(或类)来处理您的数据库。