tkbx tkbx - 1 year ago 107
Python Question

Insert line at middle of file with Python?

Is there a way to do this? Say I have a file that's a list of names that goes like this:

  1. Alfred

  2. Bill

  3. 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?

Answer Source

This is a way of doing the trick.

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

contents.insert(index, value)

f = open("path_to_file", "w")
contents = "".join(contents)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download