我有一个文本文件,我只想得到相互关联的行。尝试使用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”开头的行后面最后必须有一个不以“address family”开头的行
印刷品:
我建议使用.splitlines()函数和索引。如果可以将文件的行转换为列表,则可以使用loop If语句获取所需的标记,然后只需找到该标记并读取该行(以获得下一个连续行)
注意--如果您使用的是标准文本文件,最好将encoding='utf-8添加为open()函数的第三个参数。这将消除讨厌的字符,\n并让计算机更熟悉它实际读取的内容
请尝试下面的代码
相关问题 更多 >
编程相关推荐