python 在文本文件中查找行

python to find line within a text file

我有一个包含如下条目的文本文件:

address-object ipv4 "DRV FIL01"
name "DRV FIL01"
ID 00000000-0000-002a-0100-c0eae46ae3f4
zone LAN_General
host 10.4.12.7

address-object ipv4 "DRV FIL02"
name "DRV FIL02"
ID 00000000-0000-002b-0100-c0eae46ae3f4
zone LAN_Management
host 10.4.11.11

我需要一个 python 脚本来遍历文件,保留以下以 namehost 开头的行并忽略其余行:

name "DRV FIL01"
host 10.4.12.7

name "DRV FIL02"
host 10.4.11.11

感谢您的帮助。谢谢

试试这个代码:

file = open("file.txt")
for line in file:
    if(len(line)>3):
        if(line[0:4]=="name" or line[0:4]=="host"):
            print(line)
    if(len(line)==0):
        print()

它的作用:

  1. 打开文件

  2. 迭代文件中的行

  3. (在循环 2 中)如果行的长度至少为 4

  4. (在 if 中,共 3 个)如果以 namehost

    开头
  5. (在 if 中,共 4 个)打印行

  6. (在2的循环中)否则,如果其长度为0(表示空行)

  7. (In if of 6) 打印一个空行

这似乎是你想要的。请记住下次 post 您尝试过的代码和(如果有的话)错误消息。如果您没有任何代码,请记住 Stack Overflow 不是免费的代码编写服务,因此请先尝试一下。

基于间距和with open方法:

data = []

with open("file.txt", "r") as msg:
    for line in msg:
        if line.strip() != "":
            if line.split(' "')[0] == 'name' and line.split('" ')[1].split()[0] == 'host':
                data.append(line.strip())

print (data)

在这个版本中,您只匹配包含 name "smth" host.

的行

正则表达式版本:

import re

data = []

with open("file.txt", "r") as msg:
    for line in msg:
        if re.match(r"name.+host.+",line):
            data.append(line.strip())

print (data)

输出:

['name "DRV FIL01" host 10.4.12.7', 'name "DRV FIL02" host 10.4.11.11']

使用正则表达式版本,您可以匹配包含 'name' 和 'host'.

的所有行