2016-12-30 56 views
1

我有一些代码可以搜索与某个关键字匹配的网络共享中的文件。当找到匹配项时,我想将找到的文件复制到网络上的其他位置。我得到的错误如下:无法使用os.walk来解析路径

Traceback (most recent call last): 
File "C:/Users/user.name/PycharmProjects/SearchDirectory/Sub-Search.py", line 15, in <module> 
shutil.copy(path+name, dest) 
File "C:\Python27\lib\shutil.py", line 119, in copy 
copyfile(src, dst) 
File "C:\Python27\lib\shutil.py", line 82, in copyfile 
with open(src, 'rb') as fsrc: 
IOError: [Errno 2] No such file or directory: '//server/otheruser$/Document (user).docx' 

我相信这是因为我想找到的文件复制,而不指定它的直接路径,因为一些文件的子文件夹中找到。如果是这样,当它与关键字匹配时,如何将文件的直接路径存储到文件中?这里是我到目前为止的代码:

import os 
import shutil 


dest = '//dbserver/user.name$/Reports/User' 
path = '//dbserver/User$/' 

keyword = 'report' 

print 'Starting' 

for root, dirs, files in os.walk(path): 
    for name in files: 
     if keyword in name.lower(): 
     shutil.copy(path+name, dest) 
     print name 

print 'Done' 

PS。被访问的用户文件夹是隐藏的,因此是$。

+0

我编辑了标题,使这个问题更有可能出现在Google搜索中。我不认为网络份额在这里特别重要 –

回答

3

查看os.walk的文档,您的错误很可能是您未包含完整路径。为了避免担心后斜线和OS /特定路径分隔符等问题,您还应该考虑使用os.path.join

path+name替换为os.path.join(root, name)root元素是path下子目录的实际包含name的路径,您目前从完整路径中省略该路径。

如果您希望保留目标中的目录结构,您还应该用os.path.join(dest, os.path.relpath(root, path))替换destos.path.relpathroot减去path的路径前缀,允许您在dest下创建相同的相对路径。如果不存在正确的子文件夹,您可能需要调用os.mkdir或对他们更好,但os.makedirs,当您去:

for root, dirs, files in os.walk(path): 
    out = os.path.join(dest, os.path.relpath(root, path)) 
    #os.makedirs(out) # You may end up with empty folders if you put this line here 
    for name in files: 
     if keyword in name.lower(): 
     os.makedirs(out) # This guarantees that only folders with at least one file get created 
     shutil.copy(os.path.join(root, name), out) 

最后,考虑shutil.copytree,至极确实非常相似,你想要什么东西。唯一的缺点是它不能提供像过滤那样的东西(你正在使用的)的控制水平。