简体   繁体   English

命令仅读取文本文件的第一行

[英]Command only reads first line of text file

I have to make a program in which one of the functions is retrieval of usernames and results from a text file. 我必须编写一个程序,其中一个功能是从文本文件中检索用户名和结果。 (All on the same line) For some reason, when I run it, only the first line is printed out. (全部在同一行上)由于某种原因,当我运行它时,只打印出第一行。 Why is this ? 为什么是这样 ? Also, this only happens when I try to run the program at school (part of an assignment), it prints everything it needs to on my laptop at home. 另外,这仅在我尝试在学校运行程序时才发生(作业的一部分),它将程序打印在家里的笔记本上。 (Python versions are also the same) (Python版本也相同)

Here is my code : 这是我的代码:

def results():
       username = input("Enter username :")
       for line in open("resultsfile.txt","r"):
             if username in line:
                  print (line)
             elif username not in line:
                   ("No such user")

Also, this is what the text file looks like (without bullet points) : 另外,这是文本文件的外观(没有项目符号):

  • tud16 CS Easy 2points tud16 CS Easy 2分
  • ser23 CH Med 4points ser23 CH Med 4分
  • tud16 CS Hard 1points tud16 CS Hard 1分
def results():
    username = input("Enter username :")
    for line in open("resultsfile.txt","r"):
        if username in line:
            print (line)
        else:
            print("No such user")
results()

You are iterating over a file but you are printing No such user for every line that does not match the username . 你迭代一个文件,但是要打印No such user ,每行不的用户名相匹配

What you should do is evaluate after the loop if one of the lines in the file contained the username. 您应该做的是在循环之后评估文件中的其中一行是否包含用户名。 To implement this you could introduce a boolean ( found ) indicating if a user has been found or not: 要实现此目的,您可以引入一个布尔值( found ),指示是否已找到用户:

def results():
   found = False
   username = input("Enter username :")
   for line in open("resultsfile.txt","r"):
       if username in line:
           print (line)
           found = True
   if not found:
       print("No such user")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM