Is it better to open/close a file every time vs keeping it open until the process is finished?

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('\n')
f.close()

and

for i in range(1000):
    f=open('test2.txt', 'a')
    f.write('\n')
    f.close()

The first one takes 0.025s while the second one takes 0.309s

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)