Insert line at middle of file with Python?

python

Solution

This is a way of doing the trick.

with open("path_to_file", "r") as f:
    contents = f.readlines()

contents.insert(index, value)

with open("path_to_file", "w") as f:
    contents = "".join(contents)
    f.write(contents)

`index` and `value` are the line and value of your choice, lines starting from 0.

Problem

Is there a way to do this? Say I have a file that's a list of names that goes like this: - Alfred - Bill - Donald How could I insert the third name, "Charlie", at line x (in this case 3), and automatically send all others down one line? I've seen other questions like this, but they didn't get helpful answers. Can it be done, preferably with either a method or a loop?

Original source

Related problems