Python正则表达式获取匹配并等待新匹配

时间:2021-05-26 22:40:22

标签: python regex io

基本上它是一个更新日志文件,所以当我的函数找到下一个/最新匹配时,它会执行另一个函数 但我不希望它不断循环,只有在找到最新更新时才能工作

有没有办法可以暂停/等待它直到文件更新并获得新匹配

try:
    with open(location, "r") as f:
        for lines in f.readlines():
            for match in re.findall(pattern, lines):
                matches.append(match)
                print(match)
                time.sleep(5)
except Exception:
    pass

1 个答案:

答案 0 :(得分:0)

open() 创建一个类似文件的对象,可以使用 readline() 对其进行迭代。如果您创建一个无限循环,您将不断读取其他程序附加到文件中的任何新行。

with open(location, "r") as f:
    while True:
        line = f.readline()
        if line: #checks not None
            for match in re.findall(pattern, line)
            matches.append()
            do_work(matches) # call some other function that processes the matches that you have found