title: How to convert filename with invalid UTF-8 characters back to bytes?
body: <p>How do I convert the output of <code>os.listdir</code> to a list of <code>bytes</code> (from a list of Unicode <code>str</code>s)? It has to work even if the filename is invalid UTF-8, for example:</p>
  
  <pre><code>$ locale
  LANG=
  LANGUAGE=
  LC_CTYPE=en_US.UTF-8
  LC_NUMERIC="POSIX"
  LC_TIME="POSIX"
  LC_COLLATE="POSIX"
  LC_MONETARY="POSIX"
  LC_MESSAGES="POSIX"
  LC_PAPER="POSIX"
  LC_NAME="POSIX"
  LC_ADDRESS="POSIX"
  LC_TELEPHONE="POSIX"
  LC_MEASUREMENT="POSIX"
  LC_IDENTIFICATION="POSIX"
  LC_ALL=
  $ python3
  Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
  [GCC 4.8.2] on linux
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; import os
  &gt;&gt;&gt; open(b'\x80', 'w')
  &lt;_io.TextIOWrapper name=b'\x80' mode='w' encoding='UTF-8'&gt;
  &gt;&gt;&gt; os.listdir('.')
  ['\udc80']
  &gt;&gt;&gt; import sys
  &gt;&gt;&gt; [fn.encode(sys.getfilesystemencoding()) for fn in os.listdir('.')]
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;stdin&gt;", line 1, in &lt;listcomp&gt;
  UnicodeEncodeError: 'utf-8' codec can't encode character '\udc80' in position 0: surrogates not allowed
  &gt;&gt;&gt; [... for fn in os.listdir('.')]
  [b'\x80']
  </code></pre>
  
  <p>So what do I need to write to the <code>...</code> above to make it work?</p>
  
  <p>Please note that it's not an option to rename the file, to use Python 2.x, or to use ASCII-only filenames in this case. I'm not looking for workarounds, I'm looking for the code in place of the <code>...</code>s.</p>