简体   繁体   中英

Read text file, split by delimiter, get data from particular line and save output to file

I have a file that looks like this

[host1]
connection_type = mysql
database = master
port = 5432
host = aaa_host1

[host2]
connection_type = psql
database = master
port = 5432
host = bbb_host2

[host3]
connection_type = mysql
database = master
port = 5432
host = ccc_host3

[host4]
connection_type = mysql
database = master
port = 5432
client = aaa_host4

This file goes on with a lot of hosts. I'm trying to find each host with a particular client code (ie aaa) and output those stanzas to a file. My current code is below.

myhost = sys.argv[1]

stanzas = []
with open("/dir/to/file/file.txt") as f:
    lines = f.read()
    for entry in lines.split("\n\n"):
        for line in entry:
            if line.startswith(clientcode):
                host = line.split("=")[-1]
                if host.startswith(myhost):
                    stanzas.append(entry)

This is obviously very wrong and ugly, is there a better way to split by empty line and parse that stanza that I'm unaware of? If I added a print(line) for the for line in entry iteration it prints the letters vertically so not getting the loop right.

You can use Python's built-in configparser , since your file is valid .ini .

import configparser

def find_hosts(clientcode):
    hosts = []
    config = configparser.ConfigParser()
    config.read('file.txt')

    for host in config.sections():
        for key, value in config.items(host):
            if key == 'host' and value.startswith(clientcode):
                hosts.append(config.items(host))

    return hosts

print(find_hosts("aaa"))

Output :

[[('connection_type', 'mysql'), ('database', 'master'), ('port', '5432'), ('host', 'aaa_host1')]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM