You open the file for write-only (w mode) and try to read it - which is done by the for statement.
That is: iterating over a file with the for statement is done when you are reading the file.
If you plan to write to it, for on the fileitself can't help you - just use a normal counter with "range" and write to it.
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")
Also, writelines 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 writelines is not what you want.
(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)
update
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).
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")