gpt4 book ai didi

python - 如何通过使用确认的帐户创建功能将用户名和密码写入 csv (txt) 文件中的记录?

转载 作者:太空宇宙 更新时间:2023-11-03 18:29:04 25 4
gpt4 key购买 nike

我想知道如何将用户输入的“account”和“password_3”写入 csv (txt) 文件,作为帐户创建功能的一部分。如果“password_4”没有与“password_3”相同的输入,或者任何输入的长度为0,我还尝试循环该函数。我希望将“account”和“password_3”都写入csv( txt) 文件作为一条新记录。例如:

account_1,password_1
account_2,password_2
etc......,etc.......

这是我迄今为止想到的:

def create_account():
account = ""
print "Create Account"
# Prompts user for input of account, password and password confirmation.
account = raw_input("Enter login: ")
password_3 = raw_input("Enter passsword: ")
password_4 = raw_input("Confirm password: ")
# Sets the condition that if one input has a length of 0, the create_account function will loop.
while len(account) == 0 or len(password_3) == 0 or len(password_4) == 0:
create_account()
# Sets the condition that if the password input and password confirmation input do not match, the create_account function will loop.
while password_3 != password_4:
create_account()
# Sets the condition that if both of the coniditions set above are false, input will be stored and the loop will be broken.
else:
with open('User.csv','w',newline='') as fp:
a = csv.writer(fp,delimeter=',')
data = [account,password_3]
a.writerows(data)
## Writes input to the csv file for later use. Input is stored as one new record.

很抱歉,如果这看起来令人困惑或复杂。请注意,我对编码和 Python 完全陌生。谢谢。

最佳答案

你的程序的结构应该是这样的:

def createAccount():
account_name = raw_input('Enter login: ')
password = enterPassword()
appendAccount('User.csv', account_name, password)

def enterPassword():
while True: # repeat forever
password = raw_input('Enter password: ')
password_again = raw_input('Confirm password: ')
if len(password) < 5: # or whatever sanity check you might like
print 'Your password is too short.'
elif password != password_again:
print 'Password and confirmation do not match.'
else:
return password
# all is well; 'return' breaks the loop

def appendAccount(file_name, account_name, password):
with open(file_name, 'a') as csv_file: # Note the 'a' mode for appending
# use your writing logic, it seems fine

尽量避免函数长度超过 10 行,并努力思考最合适的名称。一个函数应该做一件明确的事情。我知道,最初几次这感觉很愚蠢,但后来你就会意识到程序变得多么可读。

关于python - 如何通过使用确认的帐户创建功能将用户名和密码写入 csv (txt) 文件中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22693340/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com