os.close(fd) is needed to avoid "The process cannot access the file because it is being used by another process" Backport of c2ab501b from master