Variable and incomplete "for" loop behavior in python

I am trying to loop on numbers between 44100000 and 44999999 in python.
I tried this:

f=open('of','w') i=44100000 while i<=44999999 : f.write(str(i)+"\n") i+=1 

but it is incomplete! tail of file:

 44999750 44999751 44999752 44999753 449997 

pay attention to the last number which

  • not the last number in the range
  • is incomplete! and does not have the same length as the others!

when I did this again, the same code gave me this tail of the file:

 44999993 44999994 44999995 44999996 44999997 44999998 

and the third run was made complete and correct:

 44999994 44999995 44999996 44999997 44999998 44999999 

when it worked correctly every time:

 for i in range(44100000,44999999): f.write('%d\n' % (i,)) 

What is the problem? Thanks

+4
source share
1 answer

You cannot close the file before completing the process. We recommend that you use resources that need to be cleaned in the with statement:

 with open('of', 'w') as f: f.write("Stuff") # f.close() will be called automatically upon leaving the with-scope 
+7
source

All Articles