Last file in a loop not written during an interpreter session

I am trying to write lists to a file. My code writes out the entire list except the last one. I do not 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.

+3


source to share


2 answers


You need to call r.close()

.


This does not happen if you run your code as a Python file, but is reproducible in the interpreter, and it does for this reason:



All changes to the file are buffered rather than immediately performed. CPython will close files when they are no longer referenced, such as when the only variable referencing them is overwritten on each iteration of your loop. (And when they are closed, all buffered changes are crossed out). In the last iteration, you never close the file, because the variable r

works. You can check this because a call exit()

in the interpreter closes the file and forces the changes to be written.


This is a motivating example for context managers and operators with

, as in inspectorG4dget's answer. They handle opening and closing files for you. Use this code instead of naming r.close()

and understand that it happens when you do it.

+9


source


Here's a much cleaner way to do the same:



complete_test=[['apple','ball'],['test','test1'],['apple','testing']]

for i,sub in enumerate(complete_list, 1):  # `enumerate` gives the index of each element in the list as well
    with open("testing{}".format(i), 'w') as outfile:  # no need to worry about opening and closing, if you use `with`
        outfile.write('\n'.join(sub))  # no need to write in a loop
        outfile.write('\n')

      

+4


source







All Articles