Reputation: 395
I have a data store in .cfg file as
Name: ABC
Age: 50
Height: 170
Weight: 60
City: Cali
I am using python and I want to find the way to process the file and access it. Currently, I use the read as txt file but it may not good solution. This is my current solution:
data = [line.rstrip('\r\n') for line in open(info.cfg)]
Upvotes: 0
Views: 46
Reputation: 1259
You need to firstly modify your config file. Add a header
[header_name]
Name: ABC
Age: 50
Height: 170
Weight: 60
City: Cali
Answer
import configparser
configParser = configparser.RawConfigParser()
configFilePath = 'config_file_name.cfg'
configParser.read(configFilePath)
print('Height : ',dict(configParser.items('header_name'))['height'])
Upvotes: 2
Reputation: 25594
Based on your example input, yaml
might be a suitable file format. You could easily import it to dict
like
import yaml
with open(file, 'r') as f:
cfg = yaml.load(f, Loader=yaml.FullLoader)
cfg
Out[20]: {'Name': 'ABC', 'Age': 50, 'Height': 170, 'Weight': 60, 'City': 'Cali'}
You can now access individual keys as
cfg['Weight']
Out[21]: 60
Upvotes: 2