How come a file doesn't get written until I stop the program?

前端 未结 7 2120
旧时难觅i
旧时难觅i 2020-11-29 03:31

I\'m running a test, and found that the file doesn\'t actually get written until I control-C to abort the program. Can anyone explain why that would happen?

I expec

7条回答
  •  死守一世寂寞
    2020-11-29 04:03

    The file does not get written, as the output buffer is not getting flushed until the garbage collection takes effect, and flushes the I/O buffer (more than likely by calling f.close()).

    Alternately, in your loop, you can call f.flush() followed by os.fsync(), as documented here.

    f.flush()
    os.fsync()
    

    All that being said, if you ever plan on sharing the data in that file with other portions of your code, I would highly recommend using a StringIO object.

提交回复
热议问题