views:

293

answers:

2

Hi,

In Python, and in general - does a close() operation on a file object imply a flush() operation?

Adam

+2  A: 

Yes. It uses the underlying close() function which does that for you. Source here.

Martin Wickman
(In other words: That file I/O is buffered is large abstracted and hidden away from you. Doing an `open`, `write`, `close` shouldn't leave stuff unwritten as that's what you already intended with `write`. A buffer that routinely eats what gets thrown at it would be quite a bad design [or a hungry buffer].)
Joey
Thanks, that was my guess too. But is this true cross-platform, cross-OS, and cross-languages?
Adam Matan
@Adam Matan: That's why Python sits on top of the C libraries. To assure that "this true cross-platform, cross-OS". I don't know what "cross-languages" means.
S.Lott
+1 Thanks. By "cross-language" I meant to ask whether this behavior is similar in the vast majority of modern programming languages.
Adam Matan
+2  A: 

NB: close() and flush() won't ensure that the data is actually secure on the disk. It just ensures that the OS has the data == that it isn't buffered inside the process.

You can try sync or fsync to get the data written to the disk.

Douglas Leeder
True, but doesn't modern OS write the data to the disk upon process termination?
Adam Matan
Depends on the time scales you are talking about. e.g. some versions of ext4 might wait whole seconds before committing your data to the disc.
Douglas Leeder
+1 If the order of magnitude is seconds, I'm quite safe. Thanks!
Adam Matan