I have a requirement to update a configuration file content at a specific lines location. How to do this in python. For example, I have a configuration file which is having below 5 lines now: 

define host{
    name kiki-server;
    XXXX XXXX;
    XXXX XXXX;
    }

I am interested have my python script to add new define statement for a new host only if the host name is not yet define in the configuration file. For example, if I run my python script to add "bouncy-server", it will append another 5 lines above this existing content. What built-in functions can help? I studied File methods, but it is missing the ability to place cursor to write new contents line to be above existing "define host{" line.    

Recommended Answers

All 2 Replies

A configuration file is usually a reasonably sized file, and you can load its content in memory as a python string or a python list of lines. You could cut this string and insert your new content as in this example:

>>> s = "foo a e ueiue uie uie define hosts{ eu ett ul uieue"
>>> idx = s.index('define hosts{')
>>> head, tail = s[:idx], s[idx:]
>>> head
'foo a e ueiue uie uie '
>>> tail
'define hosts{ eu ett ul uieue'
>>> middle = 'foo bar baz qux \n'
>>> head + middle + tail
'foo a e ueiue uie uie foo bar baz qux \ndefine hosts{ eu ett ul uieue'

Thanks for your suggestion. The string index method can help me to modify the configuration file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.