搜索正在打印结果,并且显示“未找到字符串”。状况
有人可以向我解释为什么我的条件搜索语句返回两个结果(它找到字符串并将结果打印到屏幕上,并打印“未找到字符串”)。我已经做出了改变,但我一定忽略了一些事情。
代码:
if choice == '1':
regex2 = re.compile(r'\s+')
for root,dirname, files in os.walk(directory):
for file2 in files:
if file2.endswith(".log") or file2.endswith(".txt"):
f=open(os.path.join(root, file2))
for i,line in enumerate(f.readlines()):
result2 = regex.search(re.sub(regex2, '',line))
if result2:
ln = str(i)
print "\nLine: " + ln
print "File: " + os.path.join(root,file2)
print "String Type: " + result2.group() + '\n'
temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')
else:
print "String not found!!!"
break
f.close()
re.purge()
Can someone explain to me why my conditional search statement is returning both results (it finds the string and prints the results to the screen and it prints "String Not Found"). I've made changes, but I must be overlooking something.
Code:
if choice == '1':
regex2 = re.compile(r'\s+')
for root,dirname, files in os.walk(directory):
for file2 in files:
if file2.endswith(".log") or file2.endswith(".txt"):
f=open(os.path.join(root, file2))
for i,line in enumerate(f.readlines()):
result2 = regex.search(re.sub(regex2, '',line))
if result2:
ln = str(i)
print "\nLine: " + ln
print "File: " + os.path.join(root,file2)
print "String Type: " + result2.group() + '\n'
temp.write('\nLine:' + ln + '\nString:' + result2.group() + '\nFile: ' + os.path.join(root,file2) + '\n')
else:
print "String not found!!!"
break
f.close()
re.purge()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你有一个缩进问题:
You have an indentation problem i think you want:
如果循环退出是因为它迭代的可迭代对象耗尽,而不是由于
break
语句,则执行for
循环的else
子句。由于您的循环不包含任何break
,因此else
子句将始终被执行。这是重构代码的尝试。它使用生成器函数来生成文件名列表,并使用 fileinput 模块来负责打开和关闭文件。由于
f.close()
之前的break
,您的 cod 从未显式关闭任何文件。The
else
clause to afor
loop is execute if the loop exits because the iterable it iterates over is exhausted, rather than due to abreak
statement. Since your loop doesn't include anybreak
, theelse
clause will always be executed.Here is an attempt at refactoring your code. It uses a generator function to generate the list of filenames and the
fileinput
module to take care of opening and closing the files. Your cod never explicitly closes any file due to thebreak
immediatley beforef.close()
.请稍微重构一下你的代码 - 有太多的缩进和混合控制结构。通过这种方式可以更容易地发现和纠正问题。
例如 - 将循环分为遍历和检查:
您现在看到之前代码的问题了吗?任何条件仅针对每个文件进行检查,然后再次针对每个目录进行检查。没有全局结果计数器或记录的搜索状态。
Please refactor your code a bit - there's way too much indentation and mixing control structures. It will be easier to both spot and correct the problem this way.
For example - split the loop into traversing and checking:
Do you see the problem with previous code now? Any condition was only checked per-file and then again - per-directory. There was no global counter of results, or search state recorded.