python - 对于第 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()
解决方案
以下代码背后的想法是:
- 您搜索块开始的索引
- 从那里你搜索下一个块开始的索引
- 现在您可以将相关部分从列表中切出
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]
免责声明:代码未经测试。
推荐阅读
- html - 我如何只检查 1 个 div 块而不检查其他任何内容
- ios - 如何使用字典中的键值对为表格视图单元格提供标题?
- google-chrome - 在 chrome devtools 中找不到要调试的 javascript 源映射
- javascript - 尝试从数据库中获取值时出现 Javascript“未定义”错误
- wildfly - Wildfly 18 指标微观配置文件
- geode - 远程 GFSH 启动的 @EnableClusterAware 注释 Geode 服务器需要 HTTP 配置
- python - 使用没有循环的python搜索索引
- json - 将json转为struct
- file - 如何使用 move_uploaded_file 函数加入正确的路径?
- javascript - 动画元素onScroll时如何获得精确的滚动位置