【问题标题】:python search a text file for a string and add the value to a variablepython在文本文件中搜索字符串并将值添加到变量中
【发布时间】:2014-10-20 22:56:06
【问题描述】:

我有一个这样的文本文件

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 的新变量中

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

【问题讨论】:

    标签: python string search copy


    【解决方案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]
    

    【讨论】:

    • 这段代码会打印出我想要赋值给变量 ip 的值,这段代码可以吗, ip = (next(lines).rsplit(":",1)[-1])
    • @MohammedAldaoudi,是的。它将是包含所需子字符串的行中的第一个 ip
    • 您的代码很完美,但有一个问题,我使用的是一个示例,您的代码拆分了最后一个:并复制内容。但是我的程序应该为它创建的那一行删掉 ip,所以你能编辑一下
    • 什么意思?你要重写另一个文件吗?
    • 现在如果线路是这样的 PC IP : x.x.x.x ,名称:Sarah 或 PC 名称:Sarah ,IP :x.x.x.x ,Mac :x.x.x.x 它不会打印 ip 地址
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多