Inserting Line at Specified Position of a Text File

The best way to make “pseudo-inplace” changes to a file in Python is with the fileinput module from the standard library:

import fileinput

processing_foo1s = False

for line in fileinput.input('1.txt', inplace=1):
  if line.startswith('foo1'):
    processing_foo1s = True
  else:
    if processing_foo1s:
      print 'foo bar'
    processing_foo1s = False
  print line,

You can also specify a backup extension if you want to keep the old version around, but this works in the same vein as your code — uses .bak as the backup extension but also removes it once the change has successfully completed.

Besides using the right standard library module, this code uses simpler logic: to insert a "foo bar" line after every run of lines starting with foo1, a boolean is all you need (am I inside such a run or not?) and the bool in question can be set unconditionally just based on whether the current line starts that way or not. If the precise logic you desire is slightly different from this one (which is what I deduced from your code), it shouldn’t be hard to tweak this code accordingly.

Leave a Comment