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

我有一个文件叫 xiân.txt 但是我用listdir之后得到的文件名却变为了 xian.txt ,无法使用获得的文件名打开这个文件,求大神指导,我怎么样才能用python打开或者重命名这个文件

    我都没用过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搜标题即可找到帖子。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-17
选择合适的编码追问

那怎么查看文件名是什么编码? 然后怎么选择合适的编码呢?

追答

windows文件系统一般是mbcs编码