-1

I have the text file (input.txt)

*HEADING
*NODE, NSET=ALLNODES
   1,   0.000000e+00,   0.000000e+00,   0.000000e+00
   2,   2.500000e-01,   0.000000e+00,   0.000000e+00
*ELEMENT, TYPE=S9R5, ELSET=EB1
  ...
  ...
  ...
  ...
 **
 * END OF FILE

My goal is replace all the lines between the lines (*ELEMENT, TYPE=S9R5, ELSET=EB1) and (**) with a new lines.

and keep the rest of the file unchanged. Any solution using: open('input.txt', 'w') as f1: would erase everything in the file and write the new two lines and this is not the thing I need.

D. Jadan
  • 1
  • 1
  • Welcome to SO. Unfortunately this isn't a discussion forum, tutorial or code writing service. Please take the time to read [ask] and the links it contains. You should spend some time working your way through [the Tutorial](https://docs.python.org/3/tutorial/index.html), practicing the examples. It will give you an introduction to the tools Python has to offer and you may even start to get ideas for solving your problem. – wwii Oct 29 '17 at 19:27
  • https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python – wwii Oct 29 '17 at 19:29

1 Answers1

1

This should do the job:

text = open("input.txt", "r").read()
with open("input.txt", "w") as f:
    for line in text.split("\n"):
        if "line 1" in line:
           line = line.replace("line 1", "line 3")
        elif "line 2" in line:
           line = line.replace("line 2", "line 4")
        f.write(line + "\n")

I copied out your file into a file named input.txt and tested the code exactly and it gave the right output (i.e. changed the file in the intended way), so hopefully it works for you too!

Joe Iddon
  • 20,101
  • 7
  • 33
  • 54
  • Sorry Joe but I changed the question because I do not know the content of the lines that I need to replace. All that I know is the two lines that I need to replace all the data in between. Thanks – D. Jadan Oct 29 '17 at 20:10