python访问循环内的下一行

2024-09-27 23:27:09 发布

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

以下是输入数据:

crypto map outside_map0 1 set peer 1.1.1.1
crypto map outside_map0 1 ikev1 transform-set ESP-AES-256-SHA
crypto map outside_map0 2 set peer 2.2.2.2
crypto map outside_map0 2 ikev1 transform-set ESP-AES-256-SHA
crypto map outside_map0 3 set peer 3.3.3.3
crypto map outside_map0 3 ikev1 transform-set ESP-AES-256-SHA
crypto map outside_map0 4 set peer 4.4.4.4
crypto map outside_map0 4 ikev1 transform-set ESP-3DES-SHA

我希望输出数据如下所示:

1, 1.1.1.1, ESP-AES-256-SHA
2, 2.2.2.2, ESP-AES-256-SHA
3, 3.3.3.3, ESP-AES-256-SHA
4, 4.4.4.4, ESP-3DES-SHA

我现在的剧本是这样的:

fo = open('vpn.txt', 'r')
for line in fo.readlines():
    list = line.split(" ")
    if "peer" in list:
        print list[3] + "," + list[6] + "," + next(list[6])

我很难理解下一个函数的用法。你知道吗


Tags: 数据maplinetransformcryptolistaessha
3条回答

不能在str对象旁边使用。你知道吗

下面是一个精确文件结构的解决方案

with open('vpn.txt', 'r') as fo
    desired_line = ''

    for line in fo:
        list = line.split(" ")
        if "peer" in list:
            desired_line += list[3] + "," + list[6].strip()
        else:
            desired_line += ", " + line.split(' ')[6]
            print(desired_line)
            desired_line = ''
with open("vpn.txt") as f:
    for index, (line1, line2) in enumerate(zip(f, f), start=1):
        peer_ip = line1.split()[-1]
        cipher_suite = line2.split()[-1]
        print(index, peer_ip, cipher_suite, sep=', ')

参见问题How do I read two lines from a file at a time using python

这只是每行的最后一个字,一次两行。您还需要执行一些错误检查,如

if "peer" not in line1.split(): 
    raise ValueError(f'Line {index} doesn\'t contain the word "peer", but it should: {line1}')

或者试图parse ^{} as an IP address

import ipaddress


def is_valid_ip_address(text):
    try:
        ipaddress.ipaddress(text)
        return True
    except ValueError:
        return False


with open("vpn.txt") as f:
    for index, (line1, line2) in enumerate(zip(f, f), start=1):
        peer_ip = line1.split()[-1]
        cipher_suite = line2.split()[-1]

        if not is_valid_ip_address(peer_ip):
            raise ValueError(
                f'Line couldn\'t parse "{peer_ip}" as an IP address on line {index}'
            )

        print(index, peer_ip, cipher_suite, sep=", ")

使用next函数可以做你想做的事情,但这不是解决这个问题的最简单、最容易理解的方法。我不建议在这里尝试使用next。你知道吗

您在文件中的行上有一个for循环,但是您确实希望一次读取两行,因为每个“项”数据都依赖于文件中的两行。我建议分三个部分来解决这个问题:

  1. 首先,设计一种将数据表示为对象的方法(例如元组或namedtuple)。你知道吗
  2. 编写一个while循环,一次读取文件的两行,从这两行中提取数据以创建一个对象,并在列表中收集这些对象。你知道吗
  3. 迭代对象列表,从每个对象打印出所需的数据。你知道吗

第2部分的解决方案如下所示:

results = []

with open('vpn.txt', 'r') as f:
    line1, line2 = f.readline(), f.readline()
    while line1 and line2:
        _, _, _, id_number, _, _, ip_address = line1.split()
        algorithm = line2.split()[-1]
        obj = (id_number, ip_address, algorithm)
        results.append(obj)

        line1, line2 = f.readline(), f.readline()

相关问题 更多 >

    热门问题