条件elif语句未产生正确的结果

2024-05-19 10:07:55 发布

您现在位置:Python中文网/ 问答频道 /正文

elif stament应该打印在我执行的搜索中没有找到的日志文件和路径。但是,它们会生成在单个文件中搜索的每一行(大量信息)。我做错什么了?在

 for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
      result = regex.search(whitespace.sub('', line))
      if result:
          template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
          output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

          print output
          temp.write(output)
          break
      elif not result:
          template = "\nLine: {0}\nString not found in File: {1}\nString Type: {2}\n\n"
          output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())

          print output
          temp.write(output)

  else:          
      print "There are no files in the directory!!!"

实际代码:

^{pr2}$

Tags: 文件informatoutputtypelinetemplateresult
1条回答
网友
1楼 · 发布于 2024-05-19 10:07:55

您正在遍历传递给fileinput.input(...)的每个文件的每一行,对吗?然后对每一行执行if语句。如果条件为真,则break,但如果条件为false,则不会中断,而是写入temp。因此,对于fileinput.input中与条件不匹配的每一行,都要向temp写入一行并打印output。(实际上,上面的内容是错误的,请参阅下面的编辑。)

另外,elif str(result) not in line:也会有奇怪的结果只要像其他人建议的那样使用else。如果result在这种情况下计算结果为false,那么result == None,这意味着{},这意味着如果一行包含{},那么您将得到意外的结果。在

编辑:好的,实际上,更仔细地看一下您的实际代码,严格地说,上面是错误的。但点仍然是fileinput.input()返回一个FileInput对象,该对象实质上连接文件并依次迭代每一行。因为在某些情况下,您不希望每行执行一个操作,而是针对每个文件执行一个操作,因此您必须单独地对它们进行迭代。您可以不使用fileinput来完成此操作,但既然您使用的是这种方法,我们将继续使用:

for filename in walk_dir(directory, (".log", ".txt")):
    for line in fileinput.input(filename):
        result = regex.search(whitespace.sub('', line))
        if result:
            template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
            output = template.format(fileinput.filelineno(), fileinput.filename(), result.group())
            print output
            break   # (assuming you only want to print the first result)
    else:
        ouput = fileinput.filename()
        print output
        temp.write(output)
        break

工作方式:对于列表中的每个文件,它打印文件中的第一个匹配项,如果没有找到匹配项,则打印文件名。在python中,可以将elsefor循环一起使用;如果循环没有中断,则执行循环末尾的else块。由于未找到匹配项,因此将打印文件名。在

如果您想在一个文件中打印出所有匹配项,可以将匹配项保存在一个列表中,而不是使用else,而是可以测试该列表。简化示例:

^{pr2}$

相关问题 更多 >

    热门问题