[python 2.7.5] 实现配置文件的读写

 1 import ConfigParser

 2 

 3 config = ConfigParser.RawConfigParser()

 4 

 5 # When adding sections or items, add them in the reverse order of

 6 # how you want them to be displayed in the actual file.

 7 # In addition, please note that using RawConfigParser's and the raw

 8 # mode of ConfigParser's respective set functions, you can assign

 9 # non-string values to keys internally, but will receive an error

10 # when attempting to write to a file or when you get it in non-raw

11 # mode. SafeConfigParser does not allow such assignments to take place.

12 config.add_section('Section1')

13 config.set('Section1', 'an_int', '15')

14 config.set('Section1', 'a_bool', 'true')

15 config.set('Section1', 'a_float', '3.1415')

16 config.set('Section1', 'baz', 'fun')

17 config.set('Section1', 'bar', 'Python')

18 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

19 

20 # Writing our configuration file to 'example.cfg'

21 with open('example.cfg', 'wb') as configfile:

22     config.write(configfile)

23 

24 config.read('example.cfg')

25 

26 # getfloat() raises an exception if the value is not a float

27 # getint() and getboolean() also do this for their respective types

28 a_float = config.getfloat('Section1', 'a_float')

29 an_int = config.getint('Section1', 'an_int')

30 print a_float + an_int

31 

32 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.

33 # This is because we are using a RawConfigParser().

34 if config.getboolean('Section1', 'a_bool'):

35     print config.get('Section1', 'foo')

36 

37 config = ConfigParser.ConfigParser()

38 config.read('example.cfg')

39 

40 # Set the third, optional argument of get to 1 if you wish to use raw mode.

41 print config.get('Section1', 'foo', 0) # -> "Python is fun!"

42 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"

43 

44 # The optional fourth argument is a dict with members that will take

45 # precedence in interpolation.

46 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',

47                                         'baz': 'evil'})

 

你可能感兴趣的:(python)