2017-12-03 17 views
0

저는 은행 시스템을 사용하여 파이썬을 사용하여 배우자가되는 프로젝트에 참여하고 있습니다. 나는 프로그램을 완료했으며 완벽하게 작동한다. 내가 도움이 필요한 유일한 문제는 등록을 위해 사용자 데이터를 저장할 등록 양식을 작성하고 txt 파일에서 로그인 데이터를 읽는 방법이다.파이썬에서 useres 데이터를 .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 파일에서 로그인 데이터를 읽어들이는 등록 양식을 기대합니다.

+0

.txt는 데이터를 저장하는 데 적합하지 않으며 현재 코드는 복잡합니다. 먼저, 마지막 함수 인 ThankYou()는 커널을 닫음으로써 끝난 모든 것을 지울 것입니다 (line quit()). 둘째, 아무 함수도 값을 반환하지 않거나 전역 값을 사용하지 않습니다. 셋째, 데이터 프레임을 사용하면 severals 사용자를 가질 수 있고 핀이 사용자와 일치하는지 확인한 다음 데이터 프레임에 자신의 계정에 활동을 등록 할 수 있습니다. – Mathieu

답변

0

그래서 약간 보였고 .txt 파일로 처리하려고했습니다.

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

한 PIN과 균형이 표에 의해 분리된다 :

그래서 평 파일과 같은 폴더에, 이와 같은 data.txt로 파일을 생성한다.

그런 다음 코드에서 첫 번째 단계는 전역 변수를 사용하여 PIN 번호, 잔액 및 데이터 파일 경로를 전달하는 것입니다. 그런 다음 데이터 파일이 열려 있고 저울과 핀이 2 개의 목록에 배치됩니다. 팬더와 같이 데이터 프레임 작업을 원한다면 dictionary 구조가 더 적합 할 것입니다.

# 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 '을 인쇄 (' ') 간단하게 추가 라인을 건너 뜁니다'는에 예를 들어 인쇄 된 문자열.
  • str의 중간에 값이나 str 또는 기타를두기 위해 'blabla {} ...'. format ({}에 넣을 값)을 사용하십시오. 동일한 문자열에 여러 값을 배치 할 수 있으므로 사용하는 것이 좋습니다. 그림 저장 데이터 부분에 저장합니다.

마지막으로 새 잔액은 .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() 

을 난 당신이 아이디어를 얻을 희망하고 코드 수정 직접 관리 할 수 ​​있습니다, 당신은 그것을 할 수있는 모든 키가 있어야합니다.

행운을 빈다.

+0

도움이되었지만 감사합니다.하지만 새로운 사용자를 특수 PIN으로 등록시킨 다음 .txt 파일에 쓰면 나중에 사용할 수 있습니다. – Fouad

+0

새 PIN 옵션을 함수의 어딘가에 추가하고 함수를 실행하기 전에 새 PIN 및 새 잔액 (사용자 입력)을 pin_list 및 balance_list 목록에 추가하기 만하면 data.txt 파일을 덮어 씁니다. – Mathieu