Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 45 lines
 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])

5 comments

Michal Niklas (author) 15 years, 4 months ago  # | flag

There was a bug in line 24, was:

if sections:

is:

if section:
tuco Leone 15 years, 3 months ago  # | flag

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

martin tian 13 years, 3 months ago  # | flag

SO how to compare and output the difference of the 2 .ini. files ? Thanks

Jörg Schulz 8 years, 7 months ago  # | flag

$ diff -u <(sort_ini.py foo.ini) <(sort_ini.py bar.ini)

Jörg Schulz 8 years, 7 months ago  # | flag

'[' and ']' around section names can influence sort order and should be removed before sort, e.g.

[ticket]
...
[ticket-workflow]
...

falsely results in

[ticket-workflow]
...
[ticket]
...

as '-' < ']'

Created by Michal Niklas on Wed, 17 Dec 2008 (MIT)
Python recipes (4591)
Michal Niklas's recipes (13)

Required Modules

Other Information and Tasks