3

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')
Nan Hua
  • 3,414
  • 3
  • 17
  • 24

1 Answers1

2

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')
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Specifcally, in cpython, it will likely be immediately closed. In other implementations of Python with differing GC semantics, it may stay open (and possibly unwritten) for quite some time. – Max Sep 27 '16 at 21:10