【发布时间】:2017-06-05 13:04:29
【问题描述】:
我有一组(大型)XML 文件,我想搜索其中存在的一组字符串 - 我正在尝试使用以下 Python 代码来执行此操作:
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):
然后我看到在错误发生之前发现了许多潜在的文件。
【问题讨论】:
-
也许以双斜杠
//some/path开头的路径被解释为远程SMB 路径,如\\server\shared?然后您将无法访问名为path或some的服务器。 -
附注:您的
scantree函数正在重新发明os.walk。 -
@rodrigo,如图所示,它是一个 UNC 路径,但在这种情况下可能出现的错误是
ERROR_BAD_NET_NAME(67)。获取ERROR_PATH_NOT_FOUND(3) 意味着本地设备名称不存在(例如,列出未映射的驱动器号)或未找到路径组件——除非未找到最终组件,否则错误为ERROR_FILE_NOT_FOUND(2). -
@rodigro,eryksun 是正确的,我使用的是 UNC 路径
-
@Błotosmętek 是的,我想是的!我会尝试重写...