Moon Lee
Moon Lee

Reputation: 395

Best strategy to process the structure data?

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

Answers (2)

Beyhan Gul
Beyhan Gul

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

FObersteiner
FObersteiner

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

Related Questions