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

标签 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”的第一个匹配项 然后我想复制上一行中的 ip 并将其添加到名为 ip 的新变量中

我搜索了代码,但它们都使用正常搜索并复制相同的字符串,您能帮忙吗

最佳答案

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]

关于python 在文本文件中搜索字符串并将值添加到变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476268/

相关文章:

java - 从输入字符串中的数组中搜索关键字并打印它们

java - SOLR 查询在字段开头时无法正常工作

python - 在 8 拼图游戏中用 Python 计算曼哈顿距离

string - 迭代发现定义向量条件的 bool 规则的算法

python - Kivy 无法从外部 URL 加载图像

python - 创建图时获取边权重

MySQL 中的 PHP 字符串变量 Like 查询

c++ - c++ 中的 vector 与数组

python - Gnome 中 Python 应用程序的全局热键

python - 当用 "10.0"替换 ".0"时,""被完全删除