首页 > 解决方案 > 在循环内仅打印一次输出

问题描述

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。仅当没有单个文件存在问题时,我才
需要打印,我在循环内使用 else 并且它会打印多次。请对此提出一些建议 No issues found

标签: python-3.xfor-loop

解决方案


像这样的东西应该工作:

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

推荐阅读