Read a config file in python store it into a list then split that into sublists -



Read a config file in python store it into a list then split that into sublists -

i beginner in python. may repeating same stuff.

here problem goes --> have config file called installer_data.txt (which contains)

host_ip = 10.5.5.81 services = mesos_master,hdfs_datanode,storm,kafka,zookeeper,pig host_ip = 10.6.4.31 services = mesos_slave,zookeeper,cassandra,hdfs_namenode

i trying store contents via script -->

in_file = open("installer_data.txt","r") lines = [line.rstrip('\n') line in open("installer_data.txt")] service_types =("mesos_master","mesos_slave","hdfs_namenode","hdfs_datanode","kafka","zookeeper","cassandra","pig") service = [ f f in lines if f in service_types] hosts = [ f f in lines if f not in service_types] print service[0]

error

returns traceback (most recent phone call last): file "./file_test.py", line 13, in <module> print service[0] indexerror: list index out of range

as service list not populating. can guys point me missing here?

you can parse using regular expressions, much easier!

import re #import regex string = open("data.txt","r").read() #load file regex = re.compile('(.+) = (.+)').findall(string) #look pattern (.+) = (.+) in 'string' print regex #print

this output:

[('host_ip', '10.5.5.81'), ('services', 'mesos_master,hdfs_datanode,storm,kafka,zookeeper,pig'), ('host_ip', '10.6.4.31'), ('services', 'mesos_slave,zookeeper,cassandra,hdfs_namenode')]

you can convert dictionary, create much better, becuase have variables same name in file, cant done. anyway, if want alter it, convert dict using: dict(regex), output: {'services': 'mesos_slave,zookeeper,cassandra,hdfs_namenode', 'host_ip': '10.6.4.31'}

using dictionary improve becuase can access variable name, example: regex["host_ip"]. when utilize list, can access using numbers (regex[0]), , if dont know order cant used.

python list split

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -