Ariyan
Ariyan

Reputation: 15158

variable & incomplete behavior "for" loop in python

I'm trying to loop on numbers between 44100000 to 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! the tail of the of file is:

44999750
44999751
44999752
44999753
449997

notice the last number that

  1. is not the last number in the range
  2. is incomplete! and has not the same length as the others!

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

44999993
44999994
44999995
44999996
44999997
44999998

and the third run made complete & correct out put:

44999994
44999995
44999996
44999997
44999998
44999999

while this worked correctly every time:

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

What is the problem? Thanks

Upvotes: 4

Views: 373

Answers (1)

Magnus Hoff
Magnus Hoff

Reputation: 22089

You fail to close the file before terminating the process. It is good practice to use resources that need cleaning up in a with statement:

with open('of', 'w') as f:
    f.write("Stuff")

# f.close() will be called automatically upon leaving the with-scope

Upvotes: 7

Related Questions