首页 > 解决方案 > 对于第 2 列中的给定值,基于第 1 列之前和之后打印

问题描述

这是我的 CSV 文件的样子:

1st,2nd ,3rd,4th
10.1.1.1,10.2.2.2,53,dns
10.10.10.1,10.20.20.1,80,http
,10.20.20.2,443,https
,10.20.20.3,80,http
,10.20.20.4,443,https
,10.20.20.5,80,http
10.10.10.2,10.30.30.1,22,ssh

我正在尝试搜索10.20.20.2并获取整个部分,如图所示:

我在找什么

但想不通。

这是我到目前为止的代码:

import re
import csv
                
def csv1():
    with open("sample.csv") as search:
        lines = search.readlines()
        m = '10.20.20.2'
        n = '^\d'
        match = False
        
        for line in lines:
            line = line.rstrip()
            if re.search(m, line):
                match = True
                print (line)
                continue
            elif re.match(n, line):
                match = False
                continue
            elif match:
                print (line)
                       
csv1()

标签: python

解决方案


以下代码背后的想法是:

  1. 您搜索块开始的索引
  2. 从那里你搜索下一个块开始的索引
  3. 现在您可以将相关部分从列表中切出
start = -1
end = -1

# Find the beginning index
for i, line in enumerate(lines):
    if line.startswith('10.20.20.2'):
        start = i
        break

# Find the end index
for i, line in enumerate(lines[start + 1:]):
    if not line.startswith(','):
        end = i + start
        break

# Slice the relevant parts out of your list
result = lines[start:end - 1]

免责声明:代码未经测试。


推荐阅读