Python 文件迭代和嵌套 for 循环

Python file iteration and nested for loops

我有一个 python 程序,我在其中传入一个文件,读取该文件,然后在冒号处拆分该行。 然后我打印这两个部分,对其进行一些检查并将其传递给一个函数,如果它匹配,则打印出匹配然后 returns。但是我不知道如何在我的文件中获取下一行,该程序目前只是在这一行上一遍又一遍

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、continue 和 else,以及 next(),但我似乎无法让它工作,或者它在错误的地方。 我如何从打开的文件中获取下一行,然后再次启动 for 循环以在第 3 行和第 4 行的冒号处拆分。

编辑: 我添加了 2 个中断,但我尝试将单词匹配到(对于文件名中的文件)的文件只读取第一个文件,然后从 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) 中的下一个散列,而无需扫描文件名中的所有其他文件。

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

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 更改为 return True 或 False。