'print' doesn't flush the file buffer until later. To make sure this is printed exactly when we want, we can call write() and flush() explicitly