1

There is already a question on SO that explains how to insert a line into the middle of a python file at a specific line number.

But what if I have 2 files. inputfile.txt and outputfile.txt (which already has some text) and I want to insert all of inputfile.txt (with formatting preserved) into the middle of outputfile.txt?

4
  • No OS supports inserting text into the middle of a text file. Commented Jul 16, 2018 at 2:52
  • I thought you could insert a line at a specific point into a text file, using python? stackoverflow.com/questions/10507230/… Commented Jul 16, 2018 at 2:54
  • I believe it will be the exact same as the question in the link you posted Commented Jul 16, 2018 at 2:56
  • That is not "inserting a line into a file", that is "creating a new file with the line inserted". Commented Jul 16, 2018 at 3:03

2 Answers 2

3

Why do you think it is any different from this probable SO question you are referring to?

Its just that instead of inserting a line, you need to read your inputfile.txt into a variable as shown here and insert that into the file, instead of the value as clearly shown in the question. (links provided above)

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

Comments

0

insert contents of "/inputFile.txt" into "/outputFile.txt" at line 90

with open("/inputFile.txt", "r") as f1:
    t1 = f1.readlines()
with open("/outputFile.txt", "r") as f2:
    t2 = f2.readlines()
t2.insert(90, t1)
with open("/outputFile.txt", "w") as f2:
    f2.writelines(t2)

That should do it

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.