Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last file in loop not written during interpreter session

Tags:

python

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.

like image 868
Sam Avatar asked Dec 07 '25 08:12

Sam


1 Answers

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.

like image 80
Arya McCarthy Avatar answered Dec 08 '25 21:12

Arya McCarthy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!