added missing condition to ensure file exists before trying to close it