You reopen the file in each iteration. Don't!
That open()
function (whichever language that is) certainly empties the file before it writes into, considering that w
flag you hand over. You might want to use an a
flag instead, most languages use that for "appending" to a file:
output = open("newlist.txt",'a', newline="\r\n")
But that still means that you reopen the file in every single iteration which is pretty slow. It makes more sense to open the file once before the loop. Then you can limit yourself to writing into the already opened file inside the iteration. I don't know python, but probably this is what you are looking for:
f = open("list.txt","r")
o = open("newlist.txt",'w', newline="\r\n")
for line in f:
print(line)
o.write(line)
o.close()
f.close()
@eryksun suggests in his comment below to use the with
construct of python for a more elegant and robust solution (this is python, right?). I took the liberty to include that suggestion here since it clearly makes sense. I hope I got that right:
with open("list.txt") as f, open("newlist.txt", "w", newline="\r\n") as o:
for line in f:
print(line)
o.write(line)
Looks pretty straight and logical to me, if python cleans up as @eryksun states.