Not able to frame text while adding a line to middle of file in python
<p>My text.txt looks like this</p>

<pre><code>abcd
xyzv
dead-hosts
 -abcd.srini.com
 -asdsfcd.srini.com
</code></pre>

<p>And I want to insert few lines after "dead-hosts" line, I made a script to add lines to file, there is extra space before last line, that's mandatory in my file, but post added new lines that space got removed, dont know how to maintain the space as it is.
Here is my script</p>

<pre><code>Failvrlist = ['srini.com','srini1.com']
tmplst = []
with open(âtest.txtâ,'r+') as fd:
  for line in fd:
    tmplst.append(line.strip())

  pos = tmplst.index('dead-hosts:')
  tmplst.insert(pos+1,"#extra comment ")
  for i in range(len(Failvrlist)):
    tmplst.insert(pos+2+i," - "+Failvrlist[i])
  tmplst.insert(pos+len(Failvrlist)+2,"\n")

  for i in xrange(len(tmplst)):
    fd.write("%s\n" %(tmplst[i]))
</code></pre>

<p>output is as below</p>

<pre><code>abcd
xyzv
dead-hosts
#extra comment 
 - srini.com
 - srini1.com
- abcd.srini.com
- asdsfcd.srini.com
</code></pre>

<p>if you look at the last two lines the space got removed, please advise .</p>

<p><strong>Points:</strong></p>

<ul>
<li>In you code , <code>pos = tmplst.index('dead-hosts:')</code>, you are trying to find <code>dead-hosts:</code>. However, input file you have given has only "<code>dead hosts</code>". No colon after dead-hosts, I am considering <code>dead-hosts:</code></li>
<li>While reading file first time into list, use <code>rstrip()</code> instead of <code>strip()</code>. Using rstrip() will keep spaces at the start of line as it is.</li>
<li>Once you read file into list, code after that should be outside <code>with</code> block which is use to open and read file.</li>
</ul>

<p><strong>Actually, flow of code should be</strong> </p>

<ol>
<li>Open file and read lines to list and close the file.</li>
<li>Modify list by inserting values at specific index.</li>
<li>Write the file again.</li>
</ol>

<p><strong>Code:</strong></p>

<pre><code>Failvrlist = ['srini.com','srini1.com']
tmplst = []
#Open file and read it
with open('result.txt','r+') as fd:
  for line in fd:
    tmplst.append(line.rstrip())
#Modify list
pos = tmplst.index('dead-hosts:')
tmplst.insert(pos+1,"#extra comment")
pos = tmplst.index('#extra comment')
a = 1
for i in Failvrlist:
  to_add = " -" + i
  tmplst.insert(pos+a,to_add)
  a+=1
#Write to file
with open('result.txt','w') as fd:
  for i in range(len(tmplst)):
    fd.write("%s\n" %(tmplst[i]))
</code></pre>

<p><strong>Content of result.txt:</strong></p>

<pre><code>abcd
xyzv
dead-hosts:
#extra comment
 -srini.com
 -srini1.com
 -abcd.srini.com
 -asdsfcd.srini.com
</code></pre>

python