2013-04-13 56 views
0

我使用Python 2.7刚刚开始的路径,并使用下面的代码,以确定文件路径:os.walk查找到文件的问题(Python 2.7版)

import os, fnmatch 

#find the location of sunnyexplorer.exe 
def find_files(directory, pattern): 
    for root, dirs, files in os.walk(directory): 
     for basename in files: 
      if fnmatch.fnmatch(basename, pattern): 
       filename = os.path.join(root, basename) 
       yield filename 

for filename in find_files('c:\users','*.sx2'): 
    print ('Found Sunny Explorer data in:', filename) 

寄托都似乎运作直到我尝试使用该路径并发现错误。

c:\users\woody\Documents\SMA\Sunny Explorer 

,而正确的路径是:

c:\users\woody\My Documents\SMA\Sunny Explorer 
+0

这里的代码中没有任何东西会产生不正确的路径。 'os.walk()'使用'os.listdir()',没有别的,所以你的操作系统报告那里有一个'Documents'文件夹。你确定'woody'文件夹中有* no *'Documents'文件夹吗? –

+1

'我的文档'在Windows Vista和7中被称为'文档',只是资源管理器显示不同的名称。 – filmor

回答

2

因为Vista中所有的MS Windows版本中默认情况下,在C:\Users\%username%\Documents存储用户的文档作为程序报告的路径。

但是,它们还包括指向相同位置以提供向后兼容性的NTFS junction pointC:\Users\%username%\My Documents

问题是,据我所知,你不能使用标准POSIX调用的交叉点,所以如果没有一些特定于Windows的扩展模块,Python将无法使用它们。

请参阅superuser.com上的this question

+0

非常感谢所有的帮助。 Windows资源管理器确实显示文件夹被称为“我的文档”,但我想这肯定是由于向后兼容性问题。现在我知道发生了什么,我可以修复它。再次感谢;-)伍迪 – user2277888