Python: write at the specific position in a file
<p>I have two files one having let suppose list of keys while other file have keys and value pair written like below.</p>

<blockquote>
  <p>keys```values</p>
</blockquote>

<p>Now, assuming I have to search for each keys in the later file having key value pair and on matching the keys, have to write some value for specific key at the value's position.</p>

<p>Here is my code, which on running matches the pattern, shows the exact output at the console but on writing in the file writes at the end of the file instead.</p>

<pre><code>import re
with open('perceive.txt','r') as jawabdo:
   for harsawal in jawabdo:

       with open('answers.txt','ab+') as letmethink:
           for spquestion in letmethink:
               sawal,jawab = spquestion.split("```")
               matching = re.match(sawal.lstrip('\r'),harsawal)
               if matching:
                   size = len(jawab)
                   if(size == 1):
                      jawab = "coming soon"
                      letmethink.write(jawab)
                      print('Answers written successfully!!!')
       letmethink.close()
jawabdo.close()
</code></pre>

<p><strong>Note:</strong> perceive.txt is the file with keys while answers.txt is the file having key```value pair.</p>

<p>There's no possible way to write in a specific place in a text file</p>

<p>A good alternative is:</p>

<ul>
<li>Read the file <code>everything = letmethink.read()</code></li>
<li>Insert new data <code>everything = everything[:pos] + new_data + everything[pos + 1:]</code></li>
<li>Delete the file <code>letmethink.truncate()</code></li>
<li>Completely replace the file <code>letmethink.write(everything)</code></li>
</ul>

<p>If you don't want to do this then you have to use a database and sqlite3, with which you can insert data in specific locations</p>

python file-handling