11

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
mdpoleto
  • 711
  • 2
  • 6
  • 10
  • I don't think this question is very clear. I will suggest that you add a small example of your .txt file before being processed, and then a small example of how you expect that file to look like after processing. That would probably make it much more clear what you are trying to achieve. – Dyrborg Jan 22 '14 at 14:29
  • [you have to remake a new file and write the new contents if you wish to use just python](http://stackoverflow.com/questions/125703/how-do-i-modify-a-text-file-in-python) – Siva Tumma Jan 22 '14 at 14:46
  • @sivatumma while that was my firm belief also, apparent [it ain't so](http://stackoverflow.com/a/1325927/3155195) (though of course this just auto-creates a buffer behind the scenes, as you'd expect) – zehnpaard Mar 13 '15 at 05:29

3 Answers3

21

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)
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
afkfurion
  • 2,767
  • 18
  • 12
2

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
justengel
  • 6,132
  • 4
  • 26
  • 42
1

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