Os.walk() 循环检查文件是否存在

Os.walk() loop to check if file exist or not

我在使用 os.walk 循环浏览文件夹时卡住了。 我的代码如下所示:

import os
from datetime import timedelta

startD = date(2020,7,10)
day= timedelta(days=1)
EndD = date(2020,7,13)

folder = 'somefolder'
while startD <= EndD:
    
    date=(startD.strftime("%Y%m%d"))
    file = date + 'somename'
    file2 = date + 'somene2'
    for dirpath, subdirs, files in os.walk(folder): 
        for f in files:
            if file in f or file2 in f:
                print(os.path.join(dirpath,f))
            else:
               print("no file for", date)
    startD += day

我有 4 天的时间段(从开始日期到结束日期加上 1 天),我想查找我的“文件夹”中是否存在任何文件名(文件和文件 2)。如果文件存在,我希望打印它的完整路径,但在其他情况下,我想得到通知,文件夹中没有这样的文件名(文件和文件 2)。

我故意从文件夹中删除了“file”和“file2”(适用于 11.7.2020)以检查 else 语句是否有效,但是如果我 运行 我的代码会打印“没有文件”+文件夹中每个文件的日期与定义不完全一致。

no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
no file for 20200713
ETC....

我想收到这样的结果(循环日期从 20200710 - 20200714):

path for 20200710 + 'somename'
path for 20200710 + 'somene2'
no file for 20200711 + 'somename'
no file for 20200711 + 'somene2'
path for 20200712 + 'somename'
path for 20200712 + 'somene2'
path for 20200713 + 'somename'
path for 20200713 + 'somene2'
path for 20200714 + 'somename'
path for 20200714 + 'somene2'

我知道它会循环遍历所有文件,而且很明显,对于每个没有确切文件名的文件都会打印“无文件”。 我只想打印出丢失的确切文件名,而不是全部。

也许是这样的。将 print file not found 带到循环外并使用标志 found 检查是否找到任何文件。如果循环完成并且 found 仍然是 False 然后打印 file not found

import os
from datetime import timedelta

startD = date(2020,7,10)
day= timedelta(days=1)
EndD = date(2020,7,13)

folder = 'somefolder'
while startD <= EndD:
    
    date=(startD.strftime("%Y%m%d"))
    file = date + 'somename'
    file2 = date + 'somene2'
    for dirpath, subdirs, files in os.walk(folder): 
        for f in files:
            found = False
            if file in f or file2 in f:
                print(os.path.join(dirpath,f))
                found = True
            else:
                pass
        
        if not found:
            print("no file for", date)

    startD += day