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?

Foobar
  • 7,458
  • 16
  • 81
  • 161

2 Answers2

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)

Ishan Srivastava
  • 1,129
  • 1
  • 11
  • 29
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

Pruthvi Kumar
  • 868
  • 1
  • 7
  • 15