python怎么读取文件名中包含特殊字符的文件,比如xiân.txt?

我都没用过listdit。

但是,去找了下其使用说明:

os.listdir(path)
Return a list containing the names of the entries in the directory given bypath. The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the
directory.
Availability: Unix, Windows.
Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be
a list of Unicode objects. Undecodable filenames will still be returned as
string objects.

所以:

你可以试试,传入路径是unicode,比如:

foundDirList = os.listdir(u"在这里输入你的")

然后,输出的list中的文件名列表,就都是unicode了,就可以正常显示出你要的,包括特殊字符的文件名了。

然后你就可以正常的打开了。

当然,后续处理文件时,如果是中文等非ASCII的话,也是要了解涉及到字符编码的。这时候,最好用codecs模块。如何使用,参见:

【教程】用Python的codecs处理各种字符编码的字符串和文件

这里不能贴地址,google搜标题即可找到帖子。

相关代码参考