Skip to content Skip to sidebar Skip to footer

Appending A Specific Line After Having Found It In Python

I am writing a function that allows a user to look for content in a specific line (in a file), and replace part of that content in that line, and re-writes it to the file on the sa

Solution 1:

The way you need to do this, and the way most programs do it - is to write a temporary file with the correct output, then replace the original file. This is the most fool proof way.

Here is the general logic:

  1. Open the input file, and a temporary output file.
  2. Read a line from the input file:
    1. If it matches the replacement criteria, write the new modified line to the temporary output file; otherwise write the line to the output file as-is.
  3. Once all lines have been processes, close the input file.
  4. Delete the input file.
  5. Rename the temporary file with the same name as the input file.

To implement it in Python:

import os

with open('input.txt') as i, open('output.txt', 'w') as o:
    for line in i:
       if line.startswith('Replace Me:'):
           line = 'New line, replaced the old line.\n'
       o.write(line)

os.rename('output.txt', 'input.txt')

Post a Comment for "Appending A Specific Line After Having Found It In Python"