[Tutor] Add lines to middle of text file

Steven D'Aprano steve at pearwood.info
Sun Aug 14 06:38:38 CEST 2011

Wolf Halton wrote:
> Is there a way to add text to an arbitrary place in a text file?

If you are using the OpenVMS operating system, or a VAX computer, then 
yes. The operating system natively supports inserting data into the 
middle of a file.

If you are using Windows, Linux, Unix, Mac OS (classic or X), or just 
about every other operating system I've ever come across, no. Files 
support only overwriting or appending at the end of the file.

This is why many file formats use fixed-width fields. You can seek to 
the position you want and overwrite a field with the new data.

> I need my script to add this filename to the main nagios.cfg list of read
> files, but it isn't going to work to do it as a straightforward append...
> Unless I can append it to a serverlist file and insert that file into
> nagios.cfg at the proper position...

The usual way to do that is to read the file into memory, insert the new 
data, then write the file back over the top of the old file. This could 
be as simple as this:

text = open('nagios.cfg').read()
text = modify(text)
open('nagios.cfg', 'w').write(text)

although for a production application, you would need error handling 
code to ensure things are as safe as possible. E.g.:

text = open('nagios.cfg').read()
text = modify(text)
shutil.copy('nagios.cfg', 'nagios.cfg~')  # save a backup copy
open('nagios.cfg', 'w').write(text)

Even that is pretty light on the error handling -- good enough for a 
quick and dirty script, but not for a professional quality application.


More information about the Tutor mailing list