[Tutor] A further question about opening and closing files

Alan Gauld alan.gauld at btinternet.com
Wed Sep 9 18:42:05 CEST 2015


On 09/09/15 15:24, richard kappler wrote:

>>>> f1 = open("output/test.log", 'a')
>>>> f1.write("this is a test")
>>>> f1.write("this is a test")
>>>> f1.write('why isn\'t this writing????')
>>>> f1.close()
>
> monitoring test.log as I went. Nothing was written to the file until I
> closed it, or at least that's the way it appeared to the text editor

For a short example like this its true, for a bigger example the
buffer will be flushed periodically, as it fills up.
This is not a Python thing it's an OS feature, the same is true
for any program. Its much more efficient use of the IO bus.
(Its also why you should always explicitly close a file opened
for writing - unless using with which does it for you)

You can force the writes (I see Laura has shown how) but
mostly you should just let the OS do it's thing. Otherwise
you risk cluttering up the IO bus and preventing other
programs from writing their files.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list