title: How do I convert unicode to unicode-escaped text
body: <p>I'm loading a file with a bunch of unicode characters (e.g. <code>\xe9\x87\x8b</code>). I want to convert these characters to their escaped-unicode form (<code>\u91cb</code>) in Python. I've found a couple of similar questions here on StackOverflow including this one <a href="https://stackoverflow.com/questions/26311277/evaluate-utf-8-literal-escape-sequences-in-a-string-in-python3/26311382?noredirect=1">Evaluate UTF-8 literal escape sequences in a string in Python3</a>, which does almost exactly what I want, but I can't work out how to save the data.</p>
  
  <p>For example:
  Input file:</p>
  
  <p><code>\xe9\x87\x8b</code></p>
  
  <p>Python Script</p>
  
  <pre><code>file = open("input.txt", "r")
  text = file.read()
  file.close()
  encoded = text.encode().decode('unicode-escape').encode('latin1').decode('utf-8')
  file = open("output.txt", "w")
  file.write(encoded) # fails with a unicode exception
  file.close()
  </code></pre>
  
  <p>Output File (That I would like):</p>
  
  <p><code>\u91cb</code></p>