首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用.txt文件中的数据验证用户输入

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

Stack Overflow用户
提问于 2022-05-06 21:33:38
回答 1查看 626关注 0票数 2

我到处找遍,什么都试过了。我正在创建一个游戏,在这个游戏中,用户将输入一个预先分配的引脚,并且我希望根据Python中的.txt文件验证该引脚。我尝试了这么多不同的代码行,我的结果要么一切都是有效的,要么没有什么是有效的。我做错了什么?引脚是在每一行上格式化的,并且是alpha数字,如下所示.

代码语言:javascript
复制
1DJv3Awv5
1DGw2Eql8
3JGl1Hyt7
2FHs4Etz4
3GDn9Buf8
1CEa9Aty0
2AIt9Dxz9
5DFu0Ati4
3AJu9Byi4
1EAm0Cfn1
3BEr0Gwk0
7JAf8Csf8
4HFu0Dlf4

以下是我所拥有的:

代码语言:javascript
复制
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.')
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-06 23:01:06

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

代码语言:javascript
复制
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.')

小型重构:

代码语言:javascript
复制
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(),这利用了文件对象遍历行的事实,并且对内存也更好:

代码语言:javascript
复制
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.')
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72147585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档