I'm new to python.
I wonder if I write:
open('/tmp/xxx.txt', 'w+').write('aabb')
Will the file be still opened or closed?
In another word, what's the difference between the above and
with open('/tmp/xxx.txt', 'w+') as f:
f.write('aabb')
I'm new to python.
I wonder if I write:
open('/tmp/xxx.txt', 'w+').write('aabb')
Will the file be still opened or closed?
In another word, what's the difference between the above and
with open('/tmp/xxx.txt', 'w+') as f:
f.write('aabb')
The file might stay open.
Keep in mind that it will be automatically closed upon garbage collection or software termination but it's a bad practice to count on it as exceptions, frames or even delayed GC might keep it open.
Also, you might lose data if the program terminated unexpectedly and you don't flush()
it.
In many distributions of python, where the GC is different (PyParallel for example) it might cause a big problem.
Even in CPython, it might still stay open in case of frame reference for example. Try running this:
import sys
glob_list = []
def func(*args, **kwargs):
glob_list.append((args, kwargs))
return func
sys.settrace(func)
open('/tmp/xxx.txt', 'w+').write('aabb')