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

时间:2015-06-24 02:14:53

标签: regex string python-2.7 python-3.x

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

...
一些数据
PATH = 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:' NoneType'对象没有属性' start'
我不确定为什么re.search(r' [\ n]',tempStr).start()返回无

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

应如何实施?

2 个答案:

答案 0 :(得分:0)

只要只有一行“PATH =”,以下内容就可以了:

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

答案 1 :(得分:0)

(cat filename.txt && echo -n "text to append") | final_command