Question

I have simplified my problem.

This code only writes the last text line followed by a CR/LF of the list.txt file into the newlist.txt file. How come. It prints all entries one to a line on screen, but only writes the last line to the file.

This is the crux of my first post on this topic, but I am trying to simplify the issue

f = open("list.txt","r")
for line in f:
    print(line)
    output = open("newlist.txt",'w', newline="\r\n")
    output.write(line)
f.close()
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top