使用 .txt 文件中的数据验证用户输入

Validate user input with data in .txt file

我找了又找,什么都试过了。我正在创建一个游戏,用户将在其中输入一个预先分配的 pin,我想根据 Python 中的 .txt 文件验证该 pin。我尝试了很多不同的代码行,结果是要么一切都有效,要么什么都无效。我究竟做错了什么? 每行都设置了引脚格式,并且是这样的字母数字...

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

这是我的:

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.')

尝试使用 .readlines(),这样你必须匹配整个字符串:

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.')

小重构:

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.')

事实上,您可以完全避免使用 .readlines(),这利用了文件对象遍历行的事实,并且对内存也更好:

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.')