簡體   English   中英

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'

我知道循環遍歷所有文件,並且清楚地為每個沒有確切文件名的文件打印“無文件”。 我只想打印出丟失的 EXACT 文件名,而不是全部。

也許是這樣的。 取出循環外file not found的打印file not found ,並使用found的標志來檢查是否找到任何文件。 如果循環完成並found仍為Falsefile not found打印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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM