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>You could do this by using <code>fileinput</code> with <code>inplace</code> passed. You still cannot just do a one-line edit, you much conditionally change the line you need and let everything else as is.</p>

<p>In short with a file looking like:</p>

<pre><code>$ head example.txt
pass
pass
foo
pass
</code></pre>

<p>You could do:</p>

<pre><code>import fileinput

with fileinput.input('example.txt', inplace=True) as f:
    for line in f:
        print('fah' if 'foo' in line else line.strip())
</code></pre>

<p>For a result of:</p>

<pre><code>$ head example.txt                     
pass
pass
fah
pass
</code></pre>

python file python-3.x