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>As pointed out, your issue is that you try to read and write in the same file. The easiest way is to open a new file, and replace the first one when you have the desired output.</p>

<p>To get the file lines number, you can use <a href="https://docs.python.org/2.3/whatsnew/section-enumerate.html" rel="nofollow">enumerate</a>:</p>

<pre><code>with open("test.txt",'r') as f:
                for i,line in enumerate(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>

python file file-handling