How to insert line at middle of file with Python?

Sometimes, we want to insert line at middle of file with Python.

In this article, we’ll look at how to insert line at middle of file with Python.

How to insert line at middle of file with Python?

To insert line at middle of file with Python, we can use the readlines and insert methods.

For instance, we write

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)

to open the file by calling open with the path and the permission string.

Then we call f.readlines to read the lines in the file.

Next, we call content.insert with the line index to write the line into and the value of the line.

And then we call open again to open the same file with write permission.

We have "".join(contents) to join the lines into one string.

Then we call f.write with contents to write the file contents.

Conclusion

To insert line at middle of file with Python, we can use the readlines and insert methods.