【发布时间】:2015-03-14 13:24:07
【问题描述】:
如何将os.listdir 的输出转换为bytes 的列表(来自Unicode strs 的列表)?即使文件名是无效的UTF-8,它也必须工作,例如:
$ 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.
>>> import os
>>> open(b'\x80', 'w')
<_io.TextIOWrapper name=b'\x80' mode='w' encoding='UTF-8'>
>>> os.listdir('.')
['\udc80']
>>> import sys
>>> [fn.encode(sys.getfilesystemencoding()) for fn in os.listdir('.')]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
UnicodeEncodeError: 'utf-8' codec can't encode character '\udc80' in position 0: surrogates not allowed
>>> [... for fn in os.listdir('.')]
[b'\x80']
那么我需要写信给上面的... 以使其工作吗?
请注意,在这种情况下,不能重命名文件、使用 Python 2.x 或仅使用 ASCII 文件名。我不是在寻找解决方法,而是在寻找代码来代替 ...s。
【问题讨论】:
-
您是否尝试过首先获取字节:
os.listdir(os.fsencode(os.curdir))? -
或者只是
os.listdir(b'.')...
标签: python python-3.x unicode utf-8 filesystems