简体   繁体   中英

python search a text file for a string and add the value to a variable

I have a text file like this

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

I want to SEARCH UP "from the end of the file and up" to find the FIRST Match of the string "AC:AC LP" then I want to copy the ip in the previous line and add it to a new variable named ip

i searched for codes but they all use normal search and copy the same string , could you help please

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

In a function:

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]

If the ip is not always the last element, use 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM