从文件中读取连续的两行并打印出来



我有一个文本文件,我只想获取彼此相关的行。尝试使用next()函数执行此操作,但没有成功,它抛出了StopIteration。我不确定我如何才能做到这一点,如果有人能为我指明正确的方向,我将不胜感激。

以下信息:

the expected output should look like this:
address-family ipv4 vrf vrf2 
neighbor 10.244.120.202 route-map LOCAL_PREF in 
address-family ipv4 vrf vrf3
neighbor 10.249.34.129 route-map LOCAL_PREF in
address-family ipv4 vrf vrf6
neighbor 10.242.120.202 route-map LOCAL_PREF in 
address-family ipv4 vrf vrf9
neighbor 10.246.88.2 route-map LOCAL_PREF in

>>>> text File <<<< 
address-family ipv4 vrf vrf1
address-family ipv4 vrf vrf2 
neighbor 10.244.120.202 route-map LOCAL_PREF in 
address-family ipv4 vrf vrf3
neighbor 10.249.34.129 route-map LOCAL_PREF in
address-family ipv4 vrf vrf5
address-family ipv4 vrf vrf6
neighbor 10.242.120.202 route-map LOCAL_PREF in 
address-family ipv4 vrf vrf7
address-family ipv4 vrf vrf8
address-family ipv4 vrf vrf9
neighbor 10.246.88.2 route-map LOCAL_PREF in
>>> code <<<<
with open('out_put.txt', 'r') as f:
for line in f.readlines():
if line.startswith('address-family'):
first_line = line.strip()  # strip() removes whitespace surrounding the line
print(first_line)
second_line = next(f).strip()
print(second_line)

此代码确保文件符合预期的格式,即每一行不以"address family"开头的行前面都必须有一行这样做,并且以"address family"开头的一行后面最后必须有一个不以"address family"开始的行。

previous_line = None
with open('out_put.txt', 'r') as f:
for line in f:
if line.startswith('address-family'):
previous_line = line
else:
if not previous_line:
raise Exception('Unexpected file format')
print(previous_line, end='')
print(line, end='')
previous_line = None
if previous_line is not None:
raise Exception('Unexpected file format')

打印:

address-family ipv4 vrf vrf2
neighbor 10.244.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf3
neighbor 10.249.34.129 route-map LOCAL_PREF in
address-family ipv4 vrf vrf6
neighbor 10.242.120.202 route-map LOCAL_PREF in
address-family ipv4 vrf vrf9
neighbor 10.246.88.2 route-map LOCAL_PREF in

请尝试以下代码

with open("out_put.txt","r") as f:
line=f.readline()
while(line):
if line.strip().startswith("address-family"):
line2=f.readline()
if line2 and line2.strip().startswith("neighbor"):
print(line,end='')
print(line2,end='')
line=line2
else:
line=f.readline()

我建议使用.splitlines((函数和索引。如果你可以将文件的行变成一个列表,你可以使用循环If语句来获取你想要的标记,然后只需找到标记+1的并读取该行(以获得下一个连续的行(。

附言——如果您使用的是标准文本文件,最好添加encoding='utf-8作为open((函数的第三个参数。这样可以去掉讨厌的字符,让计算机更熟悉它实际读取的内容。

下一个函数使用迭代器,在这种情况下,文件句柄as已经通过readlines((函数读取了所有文件内容,没有其他内容可读取。

您可以使用下面的索引来引用下一个连续的行

with open('out_put.txt', 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if line.startswith('address-family'):
first_line = line.strip()
print(first_line)
second_line = lines[i+1].strip()
print(second_line)

最新更新