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