Insert line at middle of file with Python?
If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following:
import fileinput
for line in fileinput.FileInput(file_path,inplace=1):
if "TEXT_TO_SEARCH" in line:
line=line.replace(line,line+"NEW_TEXT")
print line,
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.