搜索是打印结果和“未找到字符串”条件

时间:2011-06-17 15:27:17

标签: python if-statement

有人可以向我解释为什么我的条件搜索语句返回两个结果(它找到字符串并将结果打印到屏幕上并打印“String Not Found”)。我做了改变,但我必须忽视一些事情。

代码:

 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()

3 个答案:

答案 0 :(得分:3)

我认为你想要一个缩进问题:

...
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:  # <<<<<<<<<<<<<<<<<<<< HERE !!!!
        print "String not found!!!"
break
...

答案 1 :(得分:1)

请重构一下你的代码 - 压痕和混合控制结构太多了。通过这种方式发现和纠正问题会更容易。

例如 - 将循环拆分为遍历并检查:

def look_through(directory):
    found = 0
    for root, dirname, files in os.walk(directory):
        for filename in files:
            result = process_file(root, filename)
            if result is not None:
                found += 1
                yield result
    if found == 0:
        print 'blah, not found'

def process_file(...

您现在看到以前代码的问题了吗?任何条件只检查每个文件,然后再次 - 每个目录。没有全局的结果反击,或搜索状态记录。

答案 2 :(得分:1)

如果循环退出,则执行else循环的for子句,因为它迭代的迭代已经耗尽,而不是由于break语句。由于您的循环不包含任何break,因此将始终执行else子句。

以下是重构代码的尝试。它使用生成器函数生成文件名列表,并使用fileinput模块来处理打开和关闭文件。由于break之前f.close() immediatley,您的鳕鱼从未明确关闭任何文件。

def walk_dir(directory, extensions=""):
    for path, dirs, files in os.walk(directory):
        for name in files:
            if name.endswith(extensions):
                yield os.path.join(path, name)

whitespace  = re.compile(r'\s+')
for line in fileinput.input(walk_dir(directory, (".log", ".txt"))):
    result = regex.search(whitespace.sub('', line))
    if result:
        template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
        output = template.format(fileinput.filelineno(),
                                 fileinput.filename(),
                                 result.group())
        print output
        temp.write(output)