mdpoleto
mdpoleto

Reputation: 803

Adding lines after specific line

I'm trying to add specific lines to a specific area in my file. I am using this:

new_file = open("file.txt", "r+")
 for line in new_file:
  if line == "; Include below":
     line = line + "\nIncluded text"
     new_file.write(line)
  else:
     new_file.write(line)

But for some reason the content of my file.txt is duplicating.

Edit: If my file looks like:

blablablablablablabal
balablablabalablablbla
include below
blablablablablabalablab
ablablablabalbalablaba

I want make it look like:

blablablablablablabal
balablablabalablablbla
include below
included text
blablablablablabalablab
ablablablabalbalablaba

Upvotes: 12

Views: 31120

Answers (3)

afkfurion
afkfurion

Reputation: 2865

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)

Upvotes: 22

justengel
justengel

Reputation: 6320

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

Upvotes: 2

user1907906
user1907906

Reputation:

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")

Upvotes: 1

Related Questions