Use os.replace when available to avoid intermittent FileExistsError problems