>>> textdata = '''
someline
another line
real HOSTNAME
address 127.0.0.1
post 1
post 2
'''
>>> re.findall('^(.*)$\n^.*$\naddress 127.0.0.1', textdata, re.MULTILINE)
['real HOSTNAME']
lines = open("someFile", "r").read().splitlines()
IP = "10.10.1.10"
hostname = None
for i, line in enumerate(lines):
if IP in line:
hostname = lines[i - 1]
break
if hostname:
# Do stuff
from collections import deque
from itertools import takewhile
test = """
real others
address xxx.xxx.xxx
real local
address 127.0.0.1
real others
address xxx.xxx.xxx
""".split("\n")
pattern = "address 127.0.0.1"
print deque(takewhile(lambda x:x.strip()!=pattern, test), 2)[0]
regex可能是最简单的解决方案。在
您也可以使用linecache module,或者简单地使用
f.readlines()
将所有行读入一个列表中。在如果知道主机名在ip之前有多少行,则可以枚举一个行列表,并从当前索引中减去所需的行数:
这也许不是最好的解决方案,但您可以使用deque在目标线上方捕捉n条线:
将测试变量更改为file(“yourfilename”)以从文本文件中读取行。在
相关问题 更多 >
编程相关推荐