Defer tempfile close to avoid dangling FDs

Though the `tempfile` is being deleted later in the function, the file descriptor remains open.  This causes strange `ETXTBSY` errors under certain conditions.