What I want to do is (using the text below as an example), search for the string “Text2” in a text file, and then insert a line (“Inserted Text”) two lines after \"Text 2\".
You could use
f = open("file.txt","rw")
lines = f.readlines()
for i in range(len(lines)):
if lines[i].startswith("Text2"):
lines.insert(i+3,"Inserted text") #Before the line three lines after this, i.e. 2 lines later.
print "\n".join(lines)
If you load the file contents into a list, it would be easier to manipulate:
searchline = 'Text4'
lines = f.readlines() # f being the file handle
i = lines.index(searchline) # Make sure searchline is actually in the file
Now i
contains the index of the line Text4
. You can use that and list.insert(i,x)
to insert before:
lines.insert(i, 'Random text to insert')
Or after:
lines.insert(i+1, 'Different random text')
Or three lines after:
lines.insert(i+3, 'Last example text')
Just make sure to include error handling for IndexError
s and you can do with that whatever you want.
The quick-n-dirty way would be something like that
before=-1
for line in fileinput.input('file.txt', inplace=1,backup='.bak'):
if line.startswith('Text 2'):
before = 2
if before == 0
print "Inserted Text"
if before > -1
before = before - 1
print line,