Many times we need to read properties from config file. In python, you can define properties with sections. Each section can handle a related group of properties. Let's define a sample properties file and we will read it in Python.
Let's say we have a file which contains detail of countries and details of it's game. Let's call it game.properties file
game.properties
[COUNTRY]
name=India
continent=Asia
[GAME]
national=Hockey
Now let's write the python program to read this and print
#!/usr/bin/python
import os
import ConfigParser
# Initialize the parser
config = ConfigParser.RawConfigParser()
#Read properties file assuming it's in path
config.read("game.properties")
countryName = config.get('COUNTRY', 'name')
print("Country name is:" + countryName)
continentName = config.get('COUNTRY', 'continent')
print("Continent name is:" + continentName)
nationalGame = config.get('GAME', 'national')
print("National game is:" + nationalGame)
popularGame = config.get('GAME', 'popular')
print("Popular game is:" + popularGame)
No comments:
Post a Comment