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

1 投票
1 回答
2618 浏览
提问于 2025-04-28 16:24

我有一个这样的文本文件

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”。然后,我想复制它上面那一行的IP地址,并把它放到一个叫做ip的新变量里。

我找过一些代码,但它们都是用普通的搜索方式,复制的是同样的字符串,你能帮帮我吗?

暂无标签

1 个回答

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]

撰写回答