You should definitely try to open/close the file as little as possible
Because even comparing with file read/write, file open/close is far more expensive
Consider two code blocks:
f=open('test1.txt', 'w')
for i in range(1000):
f.write('
')
f.close()
and
for i in range(1000):
f=open('test2.txt', 'a')
f.write('
')
f.close()
The first one takes 0.025s while the second one takes 0.309s
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…