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>You open the file for write-only (<code>w</code> mode) and try to read it - which is done by the <code>for</code> statement.</p>

<p>That is: iterating over a file with the <code>for</code> statement is done when you are reading the file.</p>

<p>If you plan to write to it, <code>for</code> on the fileitself can't help you - just use a normal counter with "range" and write to it.</p>

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

<p>Also, <code>writelines</code> should be used when you have a list of strings you want to write,
each ina  separate line - yu don't show the content of your vaiables, but given that you want the exact line numbers, it looks like <code>writelines</code> is not what you want.</p>

<p>(On a side note - beware of indentation - you should ident a fixed ammount foreach block you enter in Python - it will work with an arbitrry identation like you did, but is not usual in Python code)</p>

<p><strong>update</strong>
It looks like you need to change just some lines of an already existing text file. The best approach for this  is by far to recreate another file, replacing the lines you want, and rename everything afterwards. 
(Writing over a text file is barely feasible, since all text lines would have to be the same size as the previously existing lines - and still would gain nothing in low-level disk access).</p>

<pre><code>import os

...

lines_to_change{
    2: serial1,
    3: serial2,
    4: serial3,
}

with open("test.txt",'rt') as input_file, open("newfile.txt", "wt") as output_file:
    for i, line in enumerate(input_file):
        if i in lines_to_change:
            output_file.write(lines_to_change[i] + '\n')
        else:
            output_file.write(line)

os.rename("test.txt", "test_old.txt")
os.rename("newfile.txt", "test.txt")
os.unlink("test_old.txt")
</code></pre>

python file file-handling