0

i.e. is the file left open when I do this:

open('filename.bla', 'wt').write(some_data)

To be clear, I am not asking if this is clean in a codebase but if there are serious consequences on the system. For example, is the file left blocked for all processes?

Sorry if this question seems dumb to some of you but I am not clear on what is really happening with open() in python.

Note: this question is similar but has no response and is not in fact as precise as what I am asking here (I think). So please make sure to mention it and provide a clear answer if this is the case, instead of simply flagging as duplicate.

Edit: I am well aware of the possibility of using a context manager with open('xxx') as f: f.write(some_data). I am not asking for another way to open but if the mentioned way is dangerous.

Romain Vincent
  • 2,875
  • 2
  • 22
  • 29
  • You should always save the return value from `open`, and use it to close the file when you're done accessing it. Another way to do this in Python is by using `with open(...) as f:` Then inside the `with` block, do `f.write(some_data)`. In this case, the file is closed after the `with` block is exited. – Tom Karzes Nov 02 '20 at 13:42
  • See https://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important . – Jussi Nurminen Nov 02 '20 at 13:49
  • It completely answers my question. Several answers stated that closing files is in fact dependant on python interpreters implementation and possibly random (thus, not reliable). Thanks all for your help . – Romain Vincent Nov 02 '20 at 13:54

0 Answers0