Writing to a file in a for loop only writes the last value

That is because you are opening , writing and closing the file 10 times inside your for loop. Opening a file in w mode erases whatever was in the file previously, so every time you open the file, the contents written to it in previous iterations get erased.

myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

You should open and close your file outside for loop.

myfile = open('xyz.txt', 'w')
for line in lines:
    var1, var2 = line.split(",");
    myfile.write("%s\n" % var1)
    
myfile.close()
text_file.close()

You should also notice to use write and not writelines.

writelines writes a list of lines to your file.

Also you should check out the answers posted by folks here that uses with statement. That is the elegant way to do file read/write operations in Python

Leave a Comment