我有用于记录用户的Python 3.5代码。
它会创建一个用户并将其记录下来。
在我终止程序并重新运行它之后,它不记得它创建的用户的详细信息。
如何将文件链接到文档?
答案 0 :(得分:0)
本周早些时候,我正在做一个类似的项目,这就是我的目标!
import csv
def displayMenu():
status = input("Are you a registered user? y/n? ")
if status == "y":
login()
elif status == "n":
newUser()
def login():
with open('users.txt') as csvfile:
reader = csv.DictReader(csvfile)
database = []
for row in reader:
database.append(dict(username=row['username'],
password=row['password'],
function=row['function']))
loggedin = False
while not loggedin:
Username = input('Fill in your username: ')
Password = input('Fill in your password: ')
for row in database:
Username_File = row['username']
Password_File = row['password']
Function_File = row['function']
if (Username_File == Username and
Password_File == Password and
Function_File == 'user'):
loggedin = True
print('Succesfully logged in as ' + Username)
elif (Username_File == Username and
Password_File == Password and
Function_File == 'admin'):
loggedin = True
print('Succesfully logged in as the admin.')
if loggedin is not True:
print ('Failed to sign in, wrong username or password.')
def newUser():
signUp = False
while not signUp:
NewUsername = input("Create login name: ")
NewUsername = str(NewUsername)
with open('users.txt', 'r') as UserData:
reader = csv.reader(UserData, delimiter=',')
if (NewUsername) in open('users.txt').read():
print ('Login name already exist!')
else:
NewPassword = input("Create password: ")
NewPassword = str(NewPassword)
with open('users.txt', 'a') as f:
writer = csv.writer(f)
UserPassFunction = (NewUsername,NewPassword,'user')
writer.writerows([UserPassFunction])
print("User created!")
signUp = True
# ---- Main ---- #
displayMenu()
答案 1 :(得分:0)
您可以读取和写入文件数据以存储用户登录详细信息,其中Logindetails.txt是存储在与程序相同位置的.txt文件。 Windows记事本使用.txt文件。
import linecache
with open("LoginDetails.txt", "r") as po:
LoginDetails = linecache.getline('LoginDetails.txt', int(LineNumber)).strip()
" R"将以只读模式打开文件。 " R +"将允许您读取和写入文件。
def replace_line(file_name, line_num, text):
lines = open(file_name, 'r').readlines()
lines[line_num] = text
with open(file_name, 'w') as out:
out.writelines(lines)
P.S我没有在这里创建这个原创帖子Editing specific line in text file in python
我建议使用SQL数据库来获取登录详细信息,如果您希望使用SQL,我建议您使用sqlite3库/模块
此外,您的计划可能无法记住我的详细信息'因为您可能会将详细信息存储为由用户输入更改的变量,该变量存储在RAM中。程序关闭后会擦除此数据,因此如果通过用户输入更改了数据,则每次关闭程序时都必须重新更改输入。
您还可以扫描文件中的字符串,例如用户名。 Search for string in txt file Python