Insert line at middle of file with Python?

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.

Leave a Comment