Q: python to find line within a text file I have a text file with entries like these:
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

I would need a python script to go through the file, keep the following lines that start with name and host and ignore the rest:
name "DRV FIL01"
host 10.4.12.7

name "DRV FIL02"
host 10.4.11.11

I appreciate any help. Thanks

A: Try this code:
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()

What it does:

*

*Open file


*iterate over lines in file


*(In loop of 2) if the length of the line is at least 4


*(In if of 3) if it starts with name or host


*(In if of 4) print the line


*(In loop of 2) otherwise, if its length is 0 (meaning empty line)


*(In if of 6) print an empty line
This seems to be what you are asking for.  Just remember next time to post the code that you have tried, and (if any) the error messages.  If you don't have any code, remember that Stack Overflow is NOT a free code writing service, so try it yourself first.

A: Based on spacing and with open method:
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)

With this version you match only lines containing name "smth" host.
And the regex version:
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)

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

With the regex version you match all lines containing 'name' and 'host'.
