【问题标题】:Search a file for a string, and execute a function if string not found; in python在文件中搜索字符串,如果找不到字符串则执行函数;在蟒蛇
【发布时间】:2010-12-24 08:12:56
【问题描述】:
def checkCache(cachedText):
    for line in open("cache"):
        if cachedText + ":" in line:
            print line
            open("cache").close()
        else:
            requestDefinition(cachedText)

此代码在文件(缓存)的每一行中搜索特定字符串(cachedText + ":")。

如果它没有找到特定字符串,则在整个文件中它意味着调用另一个函数(requestNewDefinition(cachedText))。

但是我上面的代码为每个不匹配的行执行函数。

如何在文件中搜索字符串 (cachedText + ":"),如果 在文件中的任何位置都找不到该字符串,则执行另一个函数?

示例缓存:

hello:world
foo:bar

【问题讨论】:

    标签: python string file search caching


    【解决方案1】:

    你的 for 循环坏了。您实际上是在检查文件的每一行并为每一行不匹配的行执行函数。

    另请注意,调用open("cache").close() 将重新打开缓存文件并立即关闭它,而不关闭在 for 循环开始时打开的句柄。

    执行所需操作的一种方法是使else 子句成为for 循环的一部分。 注意 for 循环中的 else 很棘手!

    def checkCache(cachedText):
        cache = open( "cache" )
        for line in cache:
            if cachedText + ":" in line:
                break
        else:
            requestDefinition(cachedText)
        cache.close()
    

    for 循环的 else 部分在循环结束时执行,前提是循环中没有调用 break

    【讨论】:

    • 必须将打开的文件分配给变量吗?是不是更快 - 或者只是更好的做法。
    • @nazarius:它允许跟踪打开的文件以关闭它。如果你经常调用这个函数,如果你不想耗尽系统资源,你真的应该关闭文件。
    • @nazarius:else 部分很棘手,因为只有在没有执行 break 时才会执行它,这与我们对 else 的期望不太一样。但是,如果这对您没有任何问题,那就完美了,您将能够毫无问题地使用 forelse 子句。
    • 哎呀,我在代码的 for 循环中犯了一个错误:我忘记使用上面一行分配的 cache 变量。我更正了我的代码。
    • 感谢大家的体贴帮助!
    【解决方案2】:

    类似这样的:

    def checkCache(cachedText):
        for line in open("cache"):
            if cachedText + ":" in line:
                print line
                break
         else:
            requestDefinition(cachedText)
    

    注意else: 是如何连接到for 的,而不是ifelse: 仅在 for 通过耗尽可迭代完成而不执行 break 时执行,这意味着在文件中的任何位置都找不到 cachedText。请参阅the Python documentation 了解更多信息。

    【讨论】:

      【解决方案3】:

      我猜你想要这样的东西。如果找到该行,则应“中断”。 "break" 将结束 for 循环。附加到 for 循环的 else 语句(与 if 语句相反)只有在 for 循环遍历每一行而没有遇到“break”条件的情况下才会执行。完成后您仍想关闭文件。

      def checkCache(cachedText):
          f = open("cache")
          for line in f:
              if cachedText + ":" in line:
                  print line
                  break
          else:
              requestDefinition(cachedText)
          f.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 2019-09-08
        • 2023-02-10
        • 1970-01-01
        • 1970-01-01
        • 2017-12-20
        • 1970-01-01
        相关资源
        最近更新 更多