2017-06-05 616 views
0

我有一个(大)的XML文件集,我想搜索一组字符串都存在 - 我试图使用以下Python代码做到这一点:os.scandir给出[WinError 3]系统找不到指定的路径

import collections 

thestrings = [] 
with open('Strings.txt') as f: 
    for line in f: 
    text = line.strip() 
    thestrings.append(text) 

print('Searching for:') 
print(thestrings) 
print('Results:') 

try: 
    from os import scandir 
except ImportError: 
    from scandir import scandir 

def scantree(path): 
    """Recursively yield DirEntry objects for given directory.""" 
    for entry in scandir(path): 
    if entry.is_dir(follow_symlinks=False) and (not entry.name.startswith('.')): 
     yield from scantree(entry.path) 
    else: 
     yield entry 

if __name__ == '__main__': 
    for entry in scantree('//path/to/folder'): 
    if ('.xml' in entry.name) and ('.zip' not in entry.name): 
     with open(entry.path) as f: 
     data = f.readline() 
     if (thestrings[0] in data): 
      print('') 
      print('****** Schema found in: ', entry.name) 
      print('') 
      data = f.read() 
      if (thestrings[1] in data) and (thestrings[2] in data) and (thestrings[3] in data): 
      print('Hit at:', entry.path) 

    print("Done!") 

哪里Strings.txt是我有兴趣,找到字符串的文件,并且第一行是架构URI。

这似乎在第一次运行正常,但在几秒钟后给了我:

FileNotFoundError: [WinError 3] The system cannot find the path specified: //some/path 

这是困惑我,因为路径运行期间,兴建?

注意,如果我仪器代码如下:

with open(entry.path) as f: 
    data = f.readline() 
    if (thestrings[0] in data): 

要成为:

with open(entry.path) as f: 
    print(entry.name) 
    data = f.readline() 
    if (thestrings[0] in data): 

然后我看到发生错误之前被人发现一些潜在的文件。

+0

可能的路径开头的双斜杠'//一些/ path'解释作为远程SMB路径,如'\\ server \ shared'?然后你无法访问名为'path'或'some'的服务器。 – rodrigo

+0

附注:你的'scantree'函数正在重新发明'os.walk'。 –

+0

@rodrigo,如图所示,它是一个UNC路径,但这种情况下可能的错误是'ERROR_BAD_NET_NAME'(67)。获取'ERROR_PATH_NOT_FOUND'(3)意味着本地设备名称不存在(例如列出未映射的驱动器盘符)或未找到路径组件 - 除非最终组件未找到,则错误为“ERROR_FILE_NOT_FOUND” (2)。 – eryksun

回答

0

我意识到,我的剧本是寻找一些很长的UNC路径名,太长的Windows似乎,所以我现在也在尝试打开文件之前检查的路径长度,如下所示:

if name.endswith('.xml'): 
    fullpath = os.path.join(root, name) 
    if (len(fullpath) > 255): ##Too long for Windows! 
    print('File-extension-based candidate: ', fullpath) 
    else: 
    if os.path.isfile(fullpath): 
     with open(fullpath) as f: 
     data = f.readline() 
     if (thestrings[0] in data): 
      print('Schema-based candidate: ', fullpath) 

注意,我还决定检查文件是否真的是一个文件,并且我改变了我的代码以使用os.walk,如上所述。随着使用.endswith()

现在一切似乎工作确定简化为.xml文件扩展名的支票......

相关问题