在python中对非英文文件名进行文件操作

时间:2013-04-05 12:05:12

标签: python windows unicode python-unicode

我们很多人可能会遇到这个问题,但我的unicode处理能力很差。这是问题: 这是一个代码片段,我试图执行.exe文件并检查文件路径是否存在但没有运气:

#Python 2.6.7

filePath = 'C:\\Test\\'  # Test folder haveing file BitComet_比特彗星_1_25.exe

for (adir, dirs, files) in os.walk(rootdir):
    for f in files:
        path = os.path.join(adir,f)
        if os.path.exists(path ):
            print'Path Found',path 
            #Extract file
            #logging(path )
        else:
            print 'Path Not Found'  
            #logging(path )

我总是得到'未找到路径'的结果。我试着使用path.decode('utf-8'):
但脚本将文件路径读为:

C:\Test\BitComet_????_1_25.exe    

由于此文件路径不存在,因此会转到else分支。

请给我一个处理此unicode问题的提示,如果我能够向用户显示cmd或日志文件中的文件路径,是否会更好。

如果这似乎是一个重复的帖子,我道歉。

1 个答案:

答案 0 :(得分:4)

Windows路径采用UTF-16编码。 Python可以为您处理此问题,只需将 unicode 路径传递给os.walk(),您将获得Unicode结果:

filePath = u'C:\\Test\\'  # Test folder haveing file BitComet_比特彗星_1_25.exe

for (adir, dirs, files) in os.walk(filePath):