python搜索字符串的文本文件并将值添加到变量中

时间:2014-10-20 22:56:07

标签: python string search copy

我有一个像这样的文本文件

PC Name : Sarah , IP : x.x.x.x
ID : AC:AC LP
PC Name : Moh, IP : x.x.x.x
ID : AC:AC LP

我想从文件的末尾“向上搜索”以查找字符串“AC:AC LP”的FIRST Match 然后我想复制前一行中的ip并将其添加到名为ip

的新变量中

我搜索了代码,但他们都使用普通搜索并复制相同的字符串,请帮忙

1 个答案:

答案 0 :(得分:1)

with open(in_file) as f:
     lines = reversed(f.readlines()) # start from end of file
     for line in lines:
         if "AC:AC LP" in line: # if AC:AC LP is in the line 
             print( next(lines).rsplit(":",1)[-1]) # go to  next line, split, get ip and break the loop
             break

在一个功能中:

def find_ip(in_file,sub_s):
    with open(in_file) as f:
        lines = reversed(f.readlines())
        for line in lines:
            if sub_s in line:
                return next(lines).rsplit(":", 1)[-1]

如果ip并不总是最后一个元素,请使用re:

def find_ip(in_file,sub_s):
    import re
    with open(in_file) as f:
        lines = reversed(f.readlines())
        for line in lines:
            if sub_s in line:
                return re.findall(r"[0-9]+(?:\.[0-9]+){3}",next(lines))[0]