os.lisdir, gets unicode, returns unicode... USUALLY?!?!?

"Martin v. Löwis" martin at v.loewis.de
Sat Nov 18 02:08:37 CET 2006

gabor schrieb:
> depends on the application. in the one where it happened i would just
> display an error message, and tell the admins to check the
> filesystem-encoding.
> (in other ones, where it's not critical to get the correct name, i would
> probably just convert the text to unicode using the "replace" behavior)
> what about using flags similar to how unicode() works? strict, ignore,
> replace and maybe keep-as-bytestring.
> like:
> os.listdir(dirname,'strict')
> i know it's not the most elegant, but it would solve most of the
> use-cases imho (at least my use-cases).

Of course, it's possible to implement this on top of the existing
listdir operation.

def failing_listdir(dirname, mode):
  result = os.listdir(dirname)
  if mode != 'strict': return result
  for r in result:
    if isinstance(r, str):
      raise UnicodeDecodeError
  return result


More information about the Python-list mailing list