如何将文件链接到文档?
答
本周早些时候我正在做一个类似的项目,这就是我所要做的!
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()
答
您可以读取和写入数据到一个文件来存储用户的登录细节,其中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)
PS我没有创建此,原帖在这里Editing specific line in text file in python
我会建议使用的登录信息SQL数据库不过,如果你想使用SQL我会建议使用sqlite3的库/模块
此外,您的程序有可能无法“记住我的详细信息”,因为您将细节存储为由用户输入更改的变量,该变量存储在RAM中。一旦程序关闭,该数据就会被清除,因此如果通过用户输入更改该数据,则每次关闭程序时都必须重新更改输入。
您也可以扫描文件中的字符串,例如用户名。 Search for string in txt file Python
请分享一些你已经尝试过的代码,如果你表明你已经为解决问题做了一些工作,那么你更有可能在这里获得帮助。 – cfreear