Python文件迭代和嵌套for循环

时间:2017-08-02 15:48:32

标签: python loops for-loop with-statement

我有一个python程序,我传入一个文件,我读取这个文件,然后将行拆分为冒号。 然后我打印这些部分,对它进行一些检查并将其传递给一个函数,如果它匹配则打印出匹配然后返回。但是我无法弄清楚如何在我的文件中获取下一行,该程序目前只是在那一行上反复进行

with open(myfile,'r') as hf:
for l in hf:
    part1 = l.split(":")[0].strip()
    part2 = l.split(":")[1].strip()


    print part1
    print part2
    print "**************"

    for file in filenames:
        print "Starting " + file
        if ".txt" in file or ".lst" in file:
            file = os.path.join(mypath, file)
            with open(file,'r') as f:
                for line in f:
                    for word in line.split():
                        ThenWord(part2,word)

我试过休息,继续和其他,以及next()但我似乎无法让它工作,或者它在错误的地方。 我如何从打开的文件中获取下一行,然后再次启动for循环以在冒号,第3行和第4行分割。

编辑: 我添加了两个中断,但我尝试匹配单词的文件(对于文件名中的文件)只读取第一个文件,然后从myfile移动到下一行。

with open(myfile,'r') as hf:
for l in hf:
    part1 = l.split(":")[0].strip()
    part2 = l.split(":")[1].strip()


    print part1
    print part2
    print "**************"

    for file in filenames:
        print "Starting " + file
        if ".txt" in file or ".lst" in file:
            file = os.path.join(mypath, file)
            with open(file,'r') as f:
                for line in f:
                    for word in line.split():
                        ThenWord(part2,word)
                        break
                break


def ThenWord(salt,word):
    salted = salt + word
    m = hashlib.md5()
    m.update(salted)
    if m.hexdigest() == hash:
        print "************ " + hash + " ************"
        print "******* Enough said - " + word + " ******* "
        return

我希望它能够在找到匹配后立即转到文件(myfile)中的下一个哈希,而不扫描文件名中的每个其他文件。

1 个答案:

答案 0 :(得分:1)

最终看来你的问题是退出深度嵌套的循环。可能的解决方案是引发异常

class MatchFoundException(Exception):
    pass


with open(myfile, 'r') as hf:
    for ...
        ...

        try:
            for file in filenames:
                ...
                        for word in line.split():
                            if ThenWord(part2, word):
                                raise MatchFoundException(('Found', part2, word))
        except MatchFoundException:
            # do something
        else:
            # optionally do something

例如,您需要更改ThenWord以返回True或False。