Exchanging out specific lines of a file
<p>I don't know if this should be obvious to the more tech savvy among us but is there a specific way to read a line out of a text file, then edit it and insert it back into the file in the original location? I have looked on the site but all the solutions I find seem to be for python 2.7. </p>

<p>Below is an example of what I am looking for:</p>

<pre><code>    with open example.txt as file:
           for line in file: 
                 if myline in file:
                     file.edit("foo","fah")
</code></pre>

<p>In 95% cases, replacing data (e.g. text) in a file usually means</p>

<ol>
<li>Read the file in chunks, e.g. line-by-line</li>
<li>Edit the chunk</li>
<li>Write the edited chunk to a new file</li>
<li>Replace the old file with a new file.</li>
</ol>

<p>So, a simple code will be:</p>

<pre><code>import os

with open(in_path, 'r') as fin:
    with open(temp_path, 'w') as fout:
        for line in fin:
            line.replace('foo', 'fah')
            fout.write(line)

os.rename(temp_path, in_path)
</code></pre>

<p>Why not in-place replacements? Well, a file is a fixed sequence of bytes, and the only way to grow it - is to append to the end of file. Now, if you want to replace the data of the same length - no problems. However if the original and new sequences' lengths differ - there is a trouble: a new sequence will be overwriting the following characters. E.g. </p>

<pre><code>original: abc hello abc world
replace abc -&gt; 12345
result: 12345ello 12345orld
</code></pre>

python file python-3.x