Modifying lines
<p>I'm looking to load a file and modify several predefined lines to certain values.
The following is what I tried:</p>

<pre><code>with open("test.txt",'w') as f:
                for i,line in f:
                    if (i == 2):
                        f.writelines(serial1)
                    if (i == 3):
                        f.writelines(serial2)
                    if (i == 4):
                        f.writelines(serial3)
                    else:
                        f.writelines(line)
</code></pre>

<p>However, when running the code I got the following error:</p>

<pre><code>for i,line in f:
io.UnsupportedOperation: not readable
</code></pre>

<p>What am I doing wrong?</p>

<p>What you are doing is called editing in place. For that, Python standard library <code>fileinput</code> can help:</p>

<pre><code>import fileinput

for line in fileinput.input('test.txt', inplace=True):
    if fileinput.lineno() == 2:
        print serial1
    elif fileinput.lineno() == 3:
        print serial2
    elif fileinput.lineno() == 4:
        print serial3
    else:
        print line
</code></pre>

<h1>Update</h1>

<p>As for "What I'm doing wrong?" there are a couple:</p>

<ul>
<li>You opened the file for writing, how can you read from it? You might attempt to change the mode from "w" to "r+", which is read and write. That brings up another dilemma: After reading line 2, the file pointer is positioned at the beginning of line 3, anything you write will overwrite line 3, not to mention the length differences between the old and new lines. It is better to write to a new temp file, then copy it back to the original when done, or you can use <code>fileinput</code> as shown above.</li>
<li><code>for i, line in f</code> does not work, I think you meant <code>for i, line in enumerate(f, 1)</code></li>
<li>What's with the extremely deep indentation?</li>
<li>The <code>if</code> statement should be <code>if ... elif ... else</code>. Currently your else clause is attached only to the <code>if i == 4</code> statement, not the other two.</li>
</ul>

python file file-handling