I am trying to write the lists into a file. My code writes all the list except last list. I don't know why. Can someone please take a look at my code and let me know what I am doing wrong?
complete_test=[['apple','ball'],['test','test1'],['apple','testing']]
counter = 1
for i in complete_test:
r=open("testing"+str(counter)+".txt",'w')
for j in i:
r.write(j+'\n')
counter=counter +1
Thank you.
You need to call r.close().
This doesn't happen if you run your code as a Python file, but it's reproducible in the interpreter, and it happens for this reason:
All of the changes to a file are buffered, rather than executed immediately. CPython will close files when there are no longer any valid references to them, such as when the only variable referencing them is overwritten on each iteration of your loop. (And when they are closed, all of the buffered changes are flushed—written out.) On the final iteration, you never close the file because the variable r sticks around. You can verify this because calling exit() in the interpreter closes the file and causes the changes to be written.
This is a motivating example for context managers and with statements, as in inspectorG4dget's answer. They handle the opening and closing of the files for you. Use that code, rather than actually calling r.close(), and understand that this is what's going when you do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With