我有一个这样的文本文件
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 - python在文本文件中搜索字符串并将值添加到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26476268/