在循环内仅打印一次输出

时间:2020-05-17 17:36:26

标签: python-3.x for-loop

for i in os.listdir(path_1):
    for j in os.listdir(path_2):
        file_name = (j.split('.')[0])
        if i.__contains__(file_name) and i.endswith('txt'):
            txt_tym = os.path.getctime(path_1 + '/' + i)
            log_tym = os.path.getctime(path_2 + '/' + j)
            if txt_tym >= log_tym:
                print('Issues found in: '+i)
            else:
                print('No issues found')

我正在使用此程序比较两个不同目录中两个文件之间的时间戳,它的名称相同但扩展名不同。
我需要在文本文档中显示结果。如果有问题,它将打印Isues found in: filename
仅当没有单个文件出现问题时,我才需要打印No issues found
在循环内使用else进行多次打印。
请对此提供一些建议

1 个答案:

答案 0 :(得分:1)

类似的事情应该起作用:

issues_found = false
for i in os.listdir(path_1):
    for j in os.listdir(path_2):
        file_name = (j.split('.')[0])
        if i.__contains__(file_name) and i.endswith('txt'):
            txt_tym = os.path.getctime(path_1 + '/' + i)
            log_tym = os.path.getctime(path_2 + '/' + j)
            if txt_tym >= log_tym:
                print('Issues found in: '+i)
                issues_found = true

if not issues_found:
    print('No issues found')