Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding lines after specific line

Tags:

python

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
like image 686
mdpoleto Avatar asked Jan 22 '14 14:01

mdpoleto


People also ask

How do you append to a specific line in Python?

Open the file in append mode ('a'). Write cursor points to the end of file. Append '\n' at the end of the file using write() function. Append the given line to the file using write() function.

How do you append a line next to a line in Python?

Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.

How do you write below a line in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.

How do you add a line to a file in Linux?

The sed command is a powerful weapon we can wield to process text under the Linux command line. For example, using the sed command, we can remove a line from a file, substitute a line, or insert a new line in a file.


2 Answers

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
like image 138
justengel Avatar answered Sep 30 '22 13:09

justengel


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)
like image 20
afkfurion Avatar answered Sep 30 '22 13:09

afkfurion