'configuration files' or 'config files' configure the initial settings for some computer programs. They are used for user applications. Files can be changed as needed. An administrator can control which protected resources an application can access, which versions of assemblies an application will use, and where remote applications and objects are located. It is important to have config files in your applications. Let look at how to implement python config file.
The 'ConfigParser' module has been renamed to 'configparser' in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3. This post I will be using Python 2. The ConfigParser class implements a basic configuration file parser language which provides a structure similar to what you would find on Microsoft Windows INI files.
1. We have to create two files. config file and python file to read this config. (Both are locate in same directory for this sample. you can locate in directory when you need)
- student.ini
- configure-reader.py
2. Add some data for configure files
The configuration file consists of sections, led by a [section] header and followed by name: value entries. Lines beginning with '#' or ';' are ignored and may be used to provide comments. Here we can below lines for configure file
1 [SectionOne]
2 Name: James
3 Value: Yes
4 Age: 30
5 Status: Single
6 Single: True
7
8
9 [SectionTwo]
10 FavouriteSport=Football
11 [SectionThree]
12 FamilyName: Johnson
13
14 [Others]
15 Route: 66
3. Let try to read this configure files in python
1 import os
2 import ConfigParser
3
4 path = os.path.dirname(os.path.realpath(__file__))
5 Config = ConfigParser.ConfigParser()
6 Config.read(path+"\\student.ini")
7 print Config.sections()
8 #==>['Others', 'SectionThree', 'SectionOne', 'SectionTwo']
4. Let modify the code more standard with function.
1 import os
2 import ConfigParser
3
4 path = os.path.dirname(os.path.realpath(__file__))
5 Config = ConfigParser.ConfigParser()
6 Config.read(path+"\\student.ini")
7
8
9 def ConfigSectionMap(section):
10 dict1 = {}
11 options = Config.options(section)
12 for option in options:
13 try:
14 dict1[option] = Config.get(section, option)
15 if dict1[option] == -1:
16 DebugPrint("skip: %s" % option)
17 except:
18 print("exception on %s!" % option)
19 dict1[option] = None
20 return dict1
21
22 Name = ConfigSectionMap("SectionOne")['name']
23 Age = ConfigSectionMap("SectionOne")['age']
24 Sport = ConfigSectionMap("SectionTwo")['favouritesport']
25 print "Hello %s. You are %s years old. %s is your favourite sport." % (Name, Age,Sport)
It is you time too. Play more with it.
No comments:
Post a Comment