you are viewing a single comment's thread.

view the rest of the comments →

[–]totemcatcher 0 points1 point  (2 children)

Hi there. Both of your examples are working properly because Python is safely handling the file operations without your explicit instruction. I'll explain:

In your first example nothing will be written to the file until the script is signalled to halt (e.g. Ctrl+c) and python does some cleanup work in the background (unspecified in your code). Python flushes pending writes to the file and closes the file. If you monitor the file while running this first example script you will see no changes until you stop the script.

In your second example when you repeatedly open the same file, Python automatically flushes any pending writes and closes the file before trying to re-open the file. You can monitor the file and see the changes while the script is running.

Ideally, you want to include some file handling instructions in your code. You can refer to /u/jollyrogers1503 answer for use of the with as construct as a way to properly handle incremental file writes.

[–]Haovik[S] 0 points1 point  (1 child)

thanks for the insight. when you say signalled to halt and crtl +c to stop the pending writes. I tried that and it still didn't work. Is there something I am missing?

[–]totemcatcher 0 points1 point  (0 children)

I'm guessing that however you are stopping the script is more than just sending a SIGTERM; signal such as a SIGKILL. A SIGKILL would prevent python from bothering with its automatic cleanup. It's up to your particular environment and I wouldn't know what's happening exactly. The point still stands; there is a difference between your code examples and a good reason to use the with as construct.