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/

相关文章:

ruby - 在 Ruby 中,将 "chomp"放在字符串开头而不是结尾的最简单方法是什么?

android - 在 android 中找到距离 db 最近的 25 个地方很慢

algorithm - 比 A* 更好的启发式

python - 为 Web 应用程序中的场所列表实现 "is open now"过滤器

c - C语言中如何检查字符串

python - 函数恰好包含 5 个元音中的每一个

java - 将文本文件拆分为 block

algorithm - 预先计算 A* 的结果

python - 三角计算器 Python

python - 如何在 Jupyter Notebook 中创建 Python 类