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

2024-09-19 23:40:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文本文件,我只想得到相互关联的行。尝试使用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)

Tags: theinmapaddresslocallinefamilyroute
3条回答

此代码确保文件符合预期格式,即不以“address family”开头的每一行前面都必须有一个以“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

我建议使用.splitlines()函数和索引。如果可以将文件的行转换为列表,则可以使用loop If语句获取所需的标记,然后只需找到该标记并读取该行(以获得下一个连续行)

注意--如果您使用的是标准文本文件,最好将encoding='utf-8添加为open()函数的第三个参数。这将消除讨厌的字符,\n并让计算机更熟悉它实际读取的内容

请尝试下面的代码

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()

相关问题 更多 >