如何检查名称中包含┤字符的文件是否存在?

时间:2013-12-31 16:00:14

标签: python python-2.7 character-encoding

我在Windows上有一个名为a┤rv.txt的文件,我想知道这个文件是否存在。

我尝试使用以下内容,但它始终返回Unsupported characters in input

>>> import os

>>> os.path.isfile("C:\Users\Zignd\Desktop\test\a┤rv.txt")

我想我需要在一些标准中编码这个字符串。我尝试过UTF-8,但它返回相同的消息。

>>> import os

>>> os.path.isfile("C:\Users\Zignd\Desktop\test\a┤rv.txt".encode('utf-8'))

我该怎么办?

修改

我正在尝试实现上面的想法列出目录中的文件,所以这里是完整的函数定义:

def imprimir(path):
    path = path.encode('utf8')
    print path
    files = os.listdir(path)
    for i in range(len(files)):
        sub = os.path.join(path, files[i])
        if os.path.isfile(sub):
            print sub

1 个答案:

答案 0 :(得分:0)

使用Windows 7上的Python 2.7,如果我在包含名为“a┤rv.txt”的文件的文件夹上执行os.listdir,则它不会显示在返回的列表中。

但是,如果我将文件夹路径设置为unicode字符串并执行os.listdir,我会得到以下名称:

d = u'C:\\Users\\mdriscoll\\Desktop'
os.listdir(d) # returns u'a\u2524rv.txt' along with a list of other files

f = u'a\u2524rv.txt'
path = os.path.join(d, f)
print os.path.isfile(path) # returns True

这适用于2.7,虽然我想不出你可以使用它的方式。