ActiveState Code

Recipe 576587: Sort sections and keys in .ini file


I use this program when I want to make .ini file more readable or compare two .ini files

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/python
# -*- coding: cp1250 -*-
__version__ = '$Id: sort_ini.py 543 2008-12-19 13:44:59Z mn $'

# author: Michal Niklas

import sys

USAGE = 'USAGE:\n\tsort_ini.py file.ini'

def sort_ini(fname):
	"""sort .ini file: sorts sections and in each section sorts keys"""
	f = file(fname)
	lines = f.readlines()
	f.close()
	section = ''
	sections = {}
	for line in lines:
		line = line.strip()
		if line:
			if line.startswith('['):
				section = line
				continue
			if section:
				try:
					sections[section].append(line)
				except KeyError:
					sections[section] = [line, ]
	if sections:
		sk = sections.keys()
		sk.sort()
		for k in sk:
			vals = sections[k]
			vals.sort()
			print k
			print '\n'.join(vals)
			print


if '--version' in sys.argv:
	print __version__
elif len(sys.argv) < 2:
	print USAGE
else:
	sort_ini(sys.argv[1])

Comments

  1. 1. At 5:48 a.m. on 19 dec 2008, Michal Niklas (the author) said:

    There was a bug in line 24, was:

    if sections:
    

    is:

    if section:
    
  2. 2. At 4:09 p.m. on 9 jan 2009, tuco Leone said:

    Maybe it is a good idea to use a more generic shebang for systems that don't have Python found in /usr/bin via the env program.

    #! /usr/bin/env python

Sign in to comment