Home > Blockchain >  Validate user input with data in .txt file
Validate user input with data in .txt file

Time:05-07

I have searched and searched and tried everything. I am creating a game where the user will input a pre-assigned pin and I want to validate that pin against a .txt file in Python. I have tried so many different lines of code and my result is either everything is valid or nothing is valid. What am I doing wrong? The pins are formatted on each line and are alpha numeric like this...

1DJv3Awv5
1DGw2Eql8
3JGl1Hyt7
2FHs4Etz4
3GDn9Buf8
1CEa9Aty0
2AIt9Dxz9
5DFu0Ati4
3AJu9Byi4
1EAm0Cfn1
3BEr0Gwk0
7JAf8Csf8
4HFu0Dlf4

Here is what I have:

user_input = input('Please enter your PIN: ')
if user_input in open("PINs.txt").read():
    print('Congratulations!  Click the button below to get your Bingo Number.')
else:
    print('The PIN you entered does not match our records.  Please check your PIN and try again.')

CodePudding user response:

Try using .readlines(), this way you have to match the whole string:

user_input = input('Please enter your PIN: ')   "\n" # Adding \n to conform to readlines
if user_input in open("PINs.txt").readlines():
    print('Congratulations!  Click the button below to get your Bingo Number.')
else:
    print('The PIN you entered does not match our records.  Please check your PIN and try again.')

Small refactoring:

with open("PINs.txt") as pinfile:  # Make sure file is closed
  user_input = input('Please enter your PIN: ')
  for pin in pinfile:  # Iterate line by line, avoid loading the whole file into memory.
    if pin.rstrip() == user_input:  # Remove newline using .rstrip()
      print('Congratulations!  Click the button below to get your Bingo Number.')
      break
  else:  # Note the indentation, the 'else' is on the 'for' loop.
    print('The PIN you entered does not match our records.  Please check your PIN and try again.')

In fact, you can avoid using .readlines() altogether, this utilizes the fact file objects iterate over lines, and is better for memory too:

user_input = input('Please enter your PIN: ')   "\n" # Adding \n to conform to readlines
if user_input in open("PINs.txt"):
    print('Congratulations!  Click the button below to get your Bingo Number.')
else:
    print('The PIN you entered does not match our records.  Please check your PIN and try again.')
  • Related