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

1 投票
1 回答
1681 浏览
提问于 2025-04-18 00:10

我在想,怎么才能把用户输入的“账号”和“密码_3”写入一个csv(txt)文件,这样就可以作为创建账号的功能的一部分。同时,我还想在“密码_4”的输入和“密码_3”不一样,或者任何输入的长度为0时,能够重新循环这个功能。我希望“账号”和“密码_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完全是新手。谢谢。

1 个回答

1

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

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行的函数,并且要认真考虑给它们起个合适的名字。一个函数应该只做一件非常明确的事情。我知道,刚开始这样做可能会觉得有点傻,但你会慢慢发现,这样写的程序更容易阅读。

撰写回答