Rename files only after file is closed

Otherwise this will break on windows where write mode also means exclusive access to the file.
"Merge pull request #330 from ionelmc/patch-1\n\nRename files only after file is closed"