【问题标题】:Checking file for text that matches input检查文件中与输入匹配的文本
【发布时间】:2018-03-12 22:42:55
【问题描述】:

我有一个需要用户名系统的程序,我希望用户输入他们的用户名,程序检查文件“用户名”以查看它是否在列表中。如果列表中只有一个人,我的下面的代码有效,否则打印正确和不正确。我将如何更改我的代码,以便如果只有一行与输入匹配,它会打印正确。

username = input("enter username: ")
search = open("username", "r")
for line in search:
    if username in line:
        print ("correct")
    else:
        print ("incorrect")

【问题讨论】:

  • 我认为这是一个低安全性的应用程序,您的用户不介意将他们的用户名存储为纯文本。 ;)
  • 是的,这只是一个测验

标签: python file loops input


【解决方案1】:

您可以利用 python 拥有的for...else 构造。

with open("username") as f:
    for line in f:
        if username in line:
            print("correct")
            break
    else:
        print("incorrect")

如果程序自然退出,则运行else 块 - 而不会从循环中中断。

【讨论】:

    【解决方案2】:

    如果你不喜欢传统的for 循环,那么我建议你这个解决方案:

    with open("username") as f:
        isInList = [username in line for line in f]:
        if any(isInList):
            print ("correct")
        else:
            print("incorrect")
    

    【讨论】:

      【解决方案3】:

      实现此目的的一种方法是在找到匹配项后简单地返回。使用 return 并将逻辑封装到函数中将允许您对结果执行其他操作。另外,我建议使用with 语句来打开文件,因为它具有更好的错误处理能力并自动负责关闭文件和清理。 Here 是关于 with 语句的简短教程。

      username = input("enter username: ")
      def read_file():
          with open("username", "r") as f:
              for line in f:
                  if username in line:
                      return "correct"
              else:
                  return "incorrect"
      result = read_file()
      print(result)
      # Or do whatever else you want with the result
      

      【讨论】:

        猜你喜欢
        • 2021-02-20
        • 1970-01-01
        • 1970-01-01
        • 2015-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多