我正在寻找一种将列表存储在电子表格中的方法,这样我既可以读取并检查帐户是否存在,也可以写入帐户,以便创建新帐户。
下面的示例仅包含用户名和密码,但我也要求在我的代码的创建帐户部分中发送电子邮件,以便也将其存储在电子表格中。
此外,我很好奇是否有人提出任何使之更加安全的提示。
userlist = ["user1","user2","user3"]
passlist = ["pass1","pass2","pass3"]
username = str(input("\n[Login to an existing account]\nUsername:"))
password = str(input("Password:"))
if username in userlist:
if password == passlist[userlist.index(username)]:
logged_in = True
答案 0 :(得分:3)
猎人,如果您真的想使用电子表格来执行此类操作,请查看XlsxWriter和OpenPyXL,但请考虑使用我们在评论中讨论的“真实”数据库!
来自OpenPyXl文档:
从工作表中阅读
from openpyxl import load_workbook
wb = load_workbook(filename='large_file.xlsx', read_only=True)
ws = wb['big_data']
for row in ws.rows:
for cell in row:
print(cell.value)
使用上述方法,您应该可以通过密码检查执行以下操作:
from openpyxl import load_workbook
wb = load_workbook(filename='userpasslist.xlsx', read_only=True)
ws = wb['userpassworksheet']
for row in ws.rows:
# assuming 1st column contains user names
if row[0].value == username:
# assuming 2nd column contains matching password
if row[1].value == password:
print("Success! Password matches! Do something here!")
else:
print("booo! Wrong password! Now git' out!")
break
From the XlsxWriter docs: Writing to a sheet
如何应用:
import xlsxwriter
# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('userpassbook.xlsx')
worksheet = workbook.add_worksheet()
# Some data we want to write to the worksheet.
users = (
['user1', 'password'],
['user2', 'password'],
['user3', 'password'],
['user4', 'password']
)
# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0
# Iterate over the data and write it out row by row.
for username, password in (users):
worksheet.write(row, col, username)
worksheet.write(row, col + 1, password)
row += 1
workbook.close()
答案 1 :(得分:2)
出于您的目的,与使用电子表格相比,读/写CSV(逗号分隔值)文件要容易得多。请注意,所有现代电子表格应用程序都可以读取CSV文件并将其显示为电子表格,也可以将电子表格导出为CSV文件。
import csv
# reading the lists from an existing CSV
with open('usernames_and_passwords.csv', 'r') as f:
reader = csv.reader(f)
userlist = [row[0] for row in reader]
passlist = [row[1] for row in reader]
# writing the Python lists to a CSV (overwrites existing files)
with open('usernames_and_passwords.csv', 'w') as f:
writer = csv.writer(f)
writer.writerows(zip(userlist, passlist))
就像上面评论中提到的@JoshuaSchlichting一样,电子表格并不是一种非常安全的存储用户信息的方式。通常,用户密码从不永远不要任何地方存储在应用程序的服务器端。应用程序通常存储每个用户密码的不可逆加密哈希,然后当用户输入密码时,应用程序将使用该哈希与新计算的哈希进行比较。这是为了防止服务器遭到黑客入侵时密码信息被泄露。
出于学习目的,使用您现有的方法很好,只是不要在公共应用程序中使用它。