-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.

2
  • Welcome to SO. Unfortunately this isn't a discussion forum, tutorial or code writing service. Please take the time to read How to Ask and the links it contains. You should spend some time working your way through the Tutorial, 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. Commented Oct 29, 2017 at 19:27
  • stackoverflow.com/questions/17140886/… Commented Oct 29, 2017 at 19:29

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.