Regex 查找并保存文本文件中的数据,直到换行字符

Regex 查找并保存文本文件中的数据,直到换行字符,regex,string,python-2.7,python-3.x,Regex,String,Python 2.7,Python 3.x,我有一个文本文件,其中包含由新行字符分隔的数据。 我正在寻找一条有路径的特定线路。 所以文件看起来像这样 … 一些数据 路径=C:\test 一些数据 … 我想收集路径并将其保存到单词path前面指定的变量 这是我目前的做法 f = open('/root/TestConnect', "r") data2 = mmap.mmap(f.fileno(),os.path.getsize(f.name),access=mmap.ACCESS_READ) index = data2.find(find_

我有一个文本文件,其中包含由新行字符分隔的数据。 我正在寻找一条有路径的特定线路。 所以文件看起来像这样


一些数据
路径=C:\test
一些数据

我想收集路径并将其保存到单词path前面指定的变量

这是我目前的做法

f = open('/root/TestConnect', "r")
data2 = mmap.mmap(f.fileno(),os.path.getsize(f.name),access=mmap.ACCESS_READ)
index = data2.find(find_str)
tempStr = repr(data2[index - 1:index + 25])

for line in tempStr:
    if line.strip() == '=':
        break
x = re.search(r'[\n]',tempStr).start()

for line in tempStr:  
    print x
if line.strip() == x:
    break
print line 
我的逻辑和实现面临多个问题

问题1:AttributeError:“非类型”对象没有属性“开始”
我不确定为什么re.search(r'[\n]',tempStr).start()返回无

问题2:我非常确定这不是提取数据的最佳方式,如果您能告诉我如何更有效地提取数据,我将不胜感激


应该如何实现这一点?

只要只有一行带有“PATH=”的代码,以下代码就可以工作:

with open('/root/TestConnect', "r") as config_file:
    for line in config_file:
        if 'PATH=' in line:
            path = line.strip().replace('PATH=','')                

我想你忘记了打印后的中断,如果我错了,请纠正我。谢谢@用户3054204如果要在第一次出现路径值时显示,则必须在
print
之后加上
break
。如果要显示所有事件,则代码可以保持不变。
import re

r = re.compile(r"\s*PATH\s*=\s*(.+)")
with open('/root/TestConnect', "rt") as f:
    for line in f.readlines():
        m = r.match(line)
        if m is not None:
            print m.group(1)