473,805 Members | 2,055 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating "Clean" INI files

56 New Member
Hello.

I've been using the ConfigParser module, which is a great module, gets the job done, but when it creates INI files its hard to read them. Heres what I mean, currently, when written to, the INI files look something like this:

Expand|Select|Wrap|Line Numbers
  1. [a]
  2. something = somethingelse
  3. [c]
  4. 5 = True
  5. 1 = false
  6. 3 = False
  7. 2 = True
  8. 4 = True
  9. [b]
  10. d = 1
  11. a = 3
  12. c = 6
  13. b = 2
I'd like to modify the module to make them look like this:

Expand|Select|Wrap|Line Numbers
  1. [a]
  2. something = somethingelse
  3. [b]
  4. a = 3
  5. b = 2
  6. c = 6
  7. d = 1
  8. [c]
  9. 1 = false
  10. 2 = True
  11. 3 = False
  12. 4 = True
  13. 5 = True
  14.  
See what I mean? Anyone have any ideas on how I can accomplish this? thanks.
May 21 '07 #1
9 2182
bartonc
6,596 Recognized Expert Expert
Hello.

I've been using the ConfigParser module, which is a great module, gets the job done, but when it creates INI files its hard to read them. Heres what I mean, currently, when written to, the INI files look something like this:

Expand|Select|Wrap|Line Numbers
  1. [a]
  2. something = somethingelse
  3. [c]
  4. 5 = True
  5. 1 = false
  6. 3 = False
  7. 2 = True
  8. 4 = True
  9. [b]
  10. d = 1
  11. a = 3
  12. c = 6
  13. b = 2
I'd like to modify the module to make them look like this:

Expand|Select|Wrap|Line Numbers
  1. [a]
  2. something = somethingelse
  3. [b]
  4. a = 3
  5. b = 2
  6. c = 6
  7. d = 1
  8. [c]
  9. 1 = false
  10. 2 = True
  11. 3 = False
  12. 4 = True
  13. 5 = True
  14.  
See what I mean? Anyone have any ideas on how I can accomplish this? thanks.
Cool... Makes me wish I was using CP. Here's the idea:
Derive from CP:
Expand|Select|Wrap|Line Numbers
  1. class MyConfigParser(ConfigParser):
  2.     # and override the write method
  3.     def write(self, fp):
  4.         # and sort the dictionary keys before calling fp.write()
.
Sounds like fun. If you need help, we're here.
May 21 '07 #2
William Manley
56 New Member
okay, sorting the sections is easy, thats just a list. but i've never sorted a dictionary before. how would i sort the keys?

Expand|Select|Wrap|Line Numbers
  1. for (key, value) in self._sections[section].items():
May 21 '07 #3
bartonc
6,596 Recognized Expert Expert
okay, sorting the sections is easy, thats just a list. but i've never sorted a dictionary before. how would i sort the keys?

Expand|Select|Wrap|Line Numbers
  1. for (key, value) in self._sections[section].items():
I know that there is a better way, but at the moment this works:
Make a list from the dict.keys(), sort it, iterate over it:

>>> d = dict(a=1,b=2,c= 3)
>>> d
{'a': 1, 'c': 3, 'b': 2}

>>> l = d.keys()
>>> l
['a', 'c', 'b']

>>> l.sort()
>>> l
['a', 'b', 'c']

>>> for key in l:
... print d[key]
...
1
2
3
>>>
May 21 '07 #4
bartonc
6,596 Recognized Expert Expert
I know that there is a better way, but at the moment this works:
Make a list from the dict.keys(), sort it, iterate over it:

>>> d = dict(a=1,b=2,c= 3)
>>> d
{'a': 1, 'c': 3, 'b': 2}

>>> l = d.keys()
>>> l
['a', 'c', 'b']

>>> l.sort()
>>> l
['a', 'b', 'c']

>>> for key in l:
... print d[key]
...
1
2
3
>>>
Expand|Select|Wrap|Line Numbers
  1. for key in l:
  2.     value = self._sections[section][key]
  3.     # ...
May 21 '07 #5
William Manley
56 New Member
Okay, this is what I came up with.

Expand|Select|Wrap|Line Numbers
  1.     def write(self, fp):
  2.         """Write an .ini-format representation of the configuration state."""
  3.         if self._defaults:
  4.             fp.write("[%s]\n" % DEFAULTSECT)
  5.             for (key, value) in self._defaults.items():
  6.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  7.             fp.write("\n")
  8.         sections = sorted(self._sections)
  9.         for section in sections:
  10.             fp.write("[%s]\n" % section)
  11.             d = self._sections[section].items()
  12.             l = sorted(d.keys())
  13.             for key in l:
  14.                 value = self._sections[section][key]
  15.                 if key != "__name__":
  16.                     fp.write("%s = %s\n" %
  17.                              (key, str(value).replace('\n', '\n\t')))
  18.             fp.write("\n")
But it generates this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\li b\ConfigParser2 .py", line 372, in write
l = sorted(d.keys() )
AttributeError: 'list' object has no attribute 'keys'
May 23 '07 #6
bartonc
6,596 Recognized Expert Expert
Okay, this is what I came up with.

Expand|Select|Wrap|Line Numbers
  1.     def write(self, fp):
  2.         """Write an .ini-format representation of the configuration state."""
  3.         if self._defaults:
  4.             fp.write("[%s]\n" % DEFAULTSECT)
  5.             for (key, value) in self._defaults.items():
  6.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  7.             fp.write("\n")
  8.         sections = sorted(self._sections)
  9.         for section in sections:
  10.             fp.write("[%s]\n" % section)
  11.             d = self._sections[section].items()
  12.             l = sorted(d.keys())
  13.             for key in l:
  14.                 value = self._sections[section][key]
  15.                 if key != "__name__":
  16.                     fp.write("%s = %s\n" %
  17.                              (key, str(value).replace('\n', '\n\t')))
  18.             fp.write("\n")
But it generates this error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python25\li b\ConfigParser2 .py", line 372, in write
l = sorted(d.keys() )
AttributeError: 'list' object has no attribute 'keys'
I'll just do a little mark up, so you'll understand what you've written:
Expand|Select|Wrap|Line Numbers
  1.     def write(self, fp):
  2.         """Write an .ini-format representation of the configuration state."""
  3.         if self._defaults:
  4.             fp.write("[%s]\n" % DEFAULTSECT)
  5.             for (key, value) in self._defaults.items():
  6.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  7.             fp.write("\n")
  8.         sections = sorted(self._sections)
  9.         for section in sections:
  10.             fp.write("[%s]\n" % section)
  11.             # dict.items returns a list of (key, value) tuples
  12.             ### d = self._sections[section].items()
  13.             # if you want you can copy the section
  14.             d = self._sections[section]
  15.             # instead of items(), we're using keys() and d[key] for the pair
  16.             l = sorted(d.keys())
  17.             for key in l:
  18.                 # then use the copy here too
  19.                 value = d[key]
  20.                 #### value = self._sections[section][key]
  21.                 if key != "__name__":
  22.                     fp.write("%s = %s\n" %
  23.                              (key, str(value).replace('\n', '\n\t')))
  24.             fp.write("\n")
Looks great otherwise.
May 23 '07 #7
bartonc
6,596 Recognized Expert Expert
I'll just do a little mark up, so you'll understand what you've written:
Expand|Select|Wrap|Line Numbers
  1.     def write(self, fp):
  2.         """Write an .ini-format representation of the configuration state."""
  3.         if self._defaults:
  4.             fp.write("[%s]\n" % DEFAULTSECT)
  5.             for (key, value) in self._defaults.items():
  6.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  7.             fp.write("\n")
  8.         sections = sorted(self._sections)
  9.         for section in sections:
  10.             fp.write("[%s]\n" % section)
  11.             # dict.items returns a list of (key, value) tuples
  12.             ### d = self._sections[section].items()
  13.             # if you want you can copy the section
  14.             d = self._sections[section]
  15.             # instead of items(), we're using keys() and d[key] for the pair
  16.             l = sorted(d.keys())
  17.             for key in l:
  18.                 # then use the copy here too
  19.                 value = d[key]
  20.                 #### value = self._sections[section][key]
  21.                 if key != "__name__":
  22.                     fp.write("%s = %s\n" %
  23.                              (key, str(value).replace('\n', '\n\t')))
  24.             fp.write("\n")
Looks great otherwise.
Looking at it, the list returned by items() may actually be sortable: you could try
Expand|Select|Wrap|Line Numbers
  1.     def write(self, fp):
  2.         """Write an .ini-format representation of the configuration state."""
  3.         if self._defaults:
  4.             fp.write("[%s]\n" % DEFAULTSECT)
  5.             for (key, value) in self._defaults.items():
  6.                 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
  7.             fp.write("\n")
  8.         sections = sorted(self._sections)
  9.         for section in sections:
  10.             fp.write("[%s]\n" % section)
  11.             # dict.items returns a list of (key, value) tuples
  12.             sectList = self._sections[section].items()
  13.             sectList.sort()
  14.             # or your sorted() trick (which is what I was trying to think of earlier)
  15.             for key, value in sectList:
  16.                 if key != "__name__":
  17.                     fp.write("%s = %s\n" %
  18.                              (key, str(value).replace('\n', '\n\t')))
  19.             fp.write("\n")
May 23 '07 #8
William Manley
56 New Member
Thanks for that, Works great.
May 24 '07 #9
bartonc
6,596 Recognized Expert Expert
Thanks for that, Works great.
You are quite welcome. Any time, really.
May 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

7
4400
by: Creative Acceleration | last post by:
Hi all, I need to convert the Query Strings into Clean URLs, Found some articles on PHP and Apache server.. How do we it them with ASP ?? Thanks Kart
4
1802
by: dmiller23462 | last post by:
Somebody take a look and give me any suggestions? My brain is nuked... Here's my deal....I have online submission forms on my intranet at work here....I am appending to an Access DB with the input from all HTML fields and then querying aforementioned DB with different variables (search by name, wave, reason, etc). The output that I'm getting (SELECT * 'cause I need all of the data included in the search) I would like to display in a nice...
3
8312
by: Nick Gilbert | last post by:
Hi, In my VS.NET 2005, if I choose Build Clean Solution, the BIN folder is not touched. Shouldn't it delete all the dll and pdb files in that folder first? Instead, I'm finding I have to do it manually. Also, when I change from Debug to Release, all the pdb files remain in the bin folder. Shouldn't these be deleted automatically? Please let me know what the "Clean Solution" is supposed to do (if it's
8
3622
by: Ulysse | last post by:
Hello, I need to clean the string like this : string = """ bonne mentalit&eacute; mec!:) \n <br>bon pour info moi je suis un serial posteur arceleur dictateur ^^* \n <br>mais pour avoir des resultats probant il faut pas faire les mariolles, comme le &quot;fondateur&quot; de bvs
25
3022
by: Koliber (js) | last post by:
sorry for my not perfect english i am really f&*ckin angry in this common pattern about dispose: ////////////////////////////////////////////////////////// Public class MyClass:IDisposable
2
3448
by: Bob Altman | last post by:
Hi, My VB project (VS 2005) has a post-build event that runs a program that creates an executable file in the target directory (that is, the same folder that contains the normal build results). However, since VS (or, more specifically, MSBuild) doesn't know about this new executable, it isn't deleted when I select Build->Clean Solution. How do I tell my VB project about this file so that it gets deleted when I "clean" the build...
3
4829
by: jcor | last post by:
Hi, I'm trying the "make distclean" comand. but I allways get this error: if I use the "make clean" I get the same error. Can someone teach me to use this commands, please? Thanks a lot, João
8
5776
by: plenty900 | last post by:
Hello, I'm trying to build a large project, and I've found that when something doesn't compile properly, and I attempt to re-build it, Visual C++ Express doesn't make a new attempt. So then I try to clean the solution, but this has literally no effect because when I try to build after that, again no attempt to made to build. Can someone tell me to really to clean the solution,
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10109
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.