我如何制作将用户数据存储在 python 中的 .txt 文件中的注册表单?

How do i make a registration form whic stores useres data in .txt file in python?

我正在做一个项目,我的配偶使用 python 创建一个 银行系统 。我已经完成了这个程序并且它运行得很好 我唯一需要帮助的问题是如何创建一个注册表单来存储用户注册数据,并从 txt 文件中读取登录数据。

                                                          =
balance = 100

def log_in():
    tries = 1
    allowed = 5
    value = True
    while tries < 5:
        print('')
        pin = input('Please Enter You 4 Digit Pin: ')
        if pin == '1234':
            print('')
            print("             Your Pin have been accepted!          ")
            print('---------------------------------------------------')
            print('')
            return True
        if not len(pin) > 0:
            tries += 1
            print('Username cant be blank, you have,',(allowed - tries),'attempts left')
            print('')
            print('---------------------------------------------------')
            print('')
        else:
            tries += 1
            print('Invalid pin, you have',(allowed - tries),'attempts left')
            print('')
            print('---------------------------------------------------')
            print('')

    print("To many incorrect tries. Could not log in")
    ThankYou()




def menu():
        print ("            Welcome to the Python Bank System")
        print (" ")
        print ("Your Transaction Options Are:")
        print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        print ("1) Deposit Money")
        print ("2) Withdraw Money")
        print ("3) Check Balance")
        print ("4) Quit Python Bank System.pyw")





def option1():
        print ('                     Deposit Money'      )
        print('')
        print("Your balance is  £ ",balance)
        Deposit=float(input("Please enter the deposit amount £ "))
        if Deposit>0:
            forewardbalance=(balance+Deposit)
            print("You've successfully deposited £", Deposit, "into your account.")
            print('Your avalible balance is £',forewardbalance)
            print('')
            print('---------------------------------------------------')
            service()

        else:
            print("No deposit was made")
            print('')
            print('---------------------------------------------------')
            service()




def option2():
    print ('                     Withdraw Money'      )
    print('')
    print("Your balance is  £ ",balance)
    Withdraw=float(input("Enter the amount you would like to Withdraw  £ "))
    if Withdraw>0:
        forewardbalance=(balance-Withdraw)
        print("You've successfully withdrawed £",Withdraw)
        print('Your avalible balance is £',forewardbalance)
    if Withdraw >= -100:
        print("yOU ARE ON OVER YOUR LIMITS !")
    else:
        print("None withdraw made")




def option3():
    print("Your balance is   £ ",balance)
    service()




def option4():
    ThankYou()


def steps():
    Option = int(input("Enter your option: "))
    print('')
    print('---------------------------------------------------')
    if Option==1:
        option1()
    if Option==2:
        option2()
    if Option==3:
        option3()
    if Option==4:
        option4()
    else:
        print('Please enter your option 1,2,3 or 4')
        steps()

def service():
    answer = input('Would you like to go to the menu? ')
    answercov = answer.lower()
    if answercov == 'yes' or answercov == 'y':
        menu()
        steps()
    else:
        ThankYou()

def ThankYou():
    print('Thank you for using Python Bank System v 1.0')
    quit()


log_in()
menu()
steps()

我希望我的程序有一个注册表单,它将存储用于注册的用户数据并从 .txt 文件中读取用于登录的数据。

所以我看了一下,并尝试用 .txt 文件来做。

因此,在与 .py 文件相同的文件夹中,创建 data.txt 文件,如下所示:

1234    1000.0
5642    500
3256    50.0
6543    25
2356    47.5
1235    495
1234    600000

密码和余额用表格分开。

然后在代码中,第一步是使用全局变量传递密码、余额和数据文件的路径。然后,打开数据文件,将余额和密码放入 2 个列表中。 如果你想使用数据框,例如熊猫,字典结构会更相关。

# Create the global variable balance and pin that will be used by the function
global balance
global pin

# Path to the data.txt file, here in the same folder as the bank.py file.
global data_path
data_path = 'data.txt'
data = open("{}".format(data_path), "r")

# Create a list of the pin, and balance in the data file.
pin_list = list()
balance_list = list()
for line in data.readlines():
    try:
        val = line.strip('\t').strip('\n').split()
        pin_list.append(val[0])
        balance_list.append(val[1])
    except:
        pass

# Close the data file    
data.close()

""" Output
pin_list = ['1234', '5642', '3256', '6543', '2356', '1235', '1234']
balance_list = ['1000', '500', '-20', '25', '47.5', '495', '600000']
"""

然后,每个修改余额的函数都需要更改全局变量值。例如:

def log_in():
    global balance
    global pin
    tries = 1
    allowed = 5
    while tries < 5:
        pin = input('\nPlease Enter You 4 Digit Pin: ')
        if pin in pin_list:
            print('\n             Your Pin have been accepted!          ')
            print('---------------------------------------------------\n')
            balance = float(balance_list[pin_list.index(pin)])
            menu()
        else:
            tries += 1
            print('Wrong PIN, you have {} attempts left.\n'.format(allowed - tries))
            print('---------------------------------------------------\n')

    print('To many incorrect tries. Could not log in.')
    ThankYou()

或者:

def option1():
    global balance
    print ('                     Deposit Money\n')
    print('Your balance is  £ {}'.format(balance))
    deposit = float(input('Please enter the deposit amount £ '))
    if deposit > 0:
        balance = balance + deposit
        print("You've successfully deposited £ {} into your account.".format(deposit))
        print('Your avalible balance is £ {}\n'.format(balance))
        print('---------------------------------------------------')
        service()

    else:
        print('No deposit was made. \n')
        print('---------------------------------------------------')
        service()

其他改进来源:

  • 不用打印 ('') 来跳过一行,只需将 '\n' 添加到打印的字符串即可。
  • 使用 'blabla {}...'.format(value to put in {}) 将值或 str 或其他任何内容放在 str 的中间。使用它很好,因为您将能够在同一个字符串中放置多个值。下面保存数据部分的说明。

最后,新余额必须保存在.txt文件中。这将在致谢功能中完成:

def ThankYou():
    global balance
    global pin
    global data_path
    balance_list[pin_list.index(pin)] = balance

    data = open("{}".format(data_path), "w")
    for i in range(len(pin_list)):
        line = '{}\t{}\n'.format(str(pin_list[i]), str(balance_list[i]))
        data.write(line)
    data.close()

    print('Thank you for using Python Bank System v 1.0')
    quit()

我希望你明白了,并且可以自己管理代码修改,你应该掌握所有的关键。

祝你好运!