This leaks an fd. Instead of throwing it away and using the name only, use:

  fd, name = mkstemp()
  ...
  tmp_index = os.fdopen(fd, 'wt')
  ...
  finally:
     tmp_index.close()
     os.unlink(tmp)