Adding lines after specific line

This is what I did.

def find_append_to_file(filename, find, insert):
    """Find and append text in a file."""
    with open(filename, 'r+') as file:
        lines = file.read()

        index = repr(lines).find(find) - 1
        if index < 0:
            raise ValueError("The text was not found in the file!")

        len_found = len(find) - 1
        old_lines = lines[index + len_found:]

        file.seek(index)
        file.write(insert)
        file.write(old_lines)
# end find_append_to_file

You cannot safely write to a file while reading, it is better to read the file into memory, update it, and rewrite it to file.

with open("file.txt", "r") as in_file:
    buf = in_file.readlines()

with open("file.txt", "w") as out_file:
    for line in buf:
        if line == "; Include this text\n":
            line = line + "Include below\n"
        out_file.write(line)

Use sed:

$ sed '/^include below/aincluded text' < file.txt

Explanation:

  • /^include below/: matches every line that starts (^) with include below
  • a: appends a newline and the following text
  • includeed text: the text that a appends

Edit: Using Python:

for line in open("file.txt").readlines():
    print(line, end="")
    if line.startswith("include below"):
        print("included text")

Tags:

Python