w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Read a config file in python store it into a list then split that into sublists

You can parse it using regular expressions, it is much easier!

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

this will 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 also convert it to a dictionary, which will make it much better, but becuase you have variables with the same name in the file, it cant be done. Anyway, if you want to change it, you convert it to dict using: dict(regex), which will output: {'services': 'mesos_slave,zookeeper,cassandra,hdfs_namenode', 'host_ip': '10.6.4.31'}

Using dictionary is better becuase you can access any variable by name, for example: regex["host_ip"]. When you use list, you can access only using numbers (regex[0]), and if you dont know the order it cant be used.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.