RYN*_*RYN 4 python loops for-loop range while-loop
我试图在python中循环44100000到44999999之间的数字.
我试过这个:
f=open('of','w')
i=44100000
while i<=44999999 :
f.write(str(i)+"\n")
i+=1
Run Code Online (Sandbox Code Playgroud)
但它不完整!of文件的尾部是:
44999750
44999751
44999752
44999753
449997
Run Code Online (Sandbox Code Playgroud)
注意最后一个数字
当我再次这样做时,相同的代码给了我这个文件尾:
44999993
44999994
44999995
44999996
44999997
44999998
Run Code Online (Sandbox Code Playgroud)
并且第三次运行完成并正确输出:
44999994
44999995
44999996
44999997
44999998
44999999
Run Code Online (Sandbox Code Playgroud)
虽然每次都正常工作:
for i in range(44100000,44999999):
f.write('%d\n' % (i,))
Run Code Online (Sandbox Code Playgroud)
问题是什么?谢谢
在终止进程之前,您无法关闭文件.优良作法是在with声明中使用需要清理的资源:
with open('of', 'w') as f:
f.write("Stuff")
# f.close() will be called automatically upon leaving the with-scope
Run Code Online (Sandbox Code Playgroud)