如何获得此脚本来检查目录中的每个文件,但不记录每个检查?

时间:2019-02-07 19:32:01

标签: python python-3.x file directory

我一直在调整此脚本,以便在工作中尝试使它对自己以外的其他用户更加友好。这是给我带来麻烦的摘要。

def depdelete(path):

    for path, dirs, files in os.walk(path):
        for f in files:
            if f.endswith('.exe'):
                os.remove(os.path.join(path, f))
                print('Dep Files have been deleted from' + path)
                with open(completeName, 'a') as ddr:
                    ddr.write('Dep Files have been deleted from' + path + '. \n')
            else:
                print('No Dep Files found in' + path)
                with open(completeName, 'a') as ddr:
                    ddr.write('No Further Dep Files found in' + path + '. \n')

现在,脚本可以按预期工作。文件被删除并正确记录。但是,在当前状态下,Else语句针对路径中的每个文件运行,从而导致重复的条目“在...中找不到更多的Dep文件”。

我想对此进行更改,以便它检查每个文件,但是在检查了整个文件之后,只记录了一个“在...中找不到进一步的Dep文件”实例。

基本上,我该如何对目录中的每个文件进行 check ,但是在检查完每个文件之后,只记录一次“在...中找不到其他Dep文件”。

现在有点消隐,有一种“在我的舌尖上”的感觉。提示?

2 个答案:

答案 0 :(得分:0)

改为使用标志。

def depdelete(path):

    for path, dirs, files in os.walk(path):
        for f in files:
            found = False              # Add a boolean as flag, reset each iteration
            if f.endswith('.exe'):
                found = True           # Set the flag so "No further..." will not be triggered
                os.remove(os.path.join(path, f))
                print('Dep Files have been deleted from' + path)
                with open(completeName, 'a') as ddr:
                    ddr.write('Dep Files have been deleted from' + path + '. \n')
            if not found:              # check the flag
                print('No Dep Files found in' + path)
                with open(completeName, 'a') as ddr:
                    ddr.write('No Further Dep Files found in' + path + '. \n')

答案 1 :(得分:0)

这似乎只需要一点重组。

def depdelete(path):

    wereThereAnyDepFiles = False

    for path, dirs, files in os.walk(path):
        for f in files:
            if f.endswith('.exe'):
                os.remove(os.path.join(path, f))
                print('Dep Files have been deleted from' + path)
                with open(completeName, 'a') as ddr:
                    ddr.write('Dep Files have been deleted from' + path + '. \n')
                wereThereAnyDepFiles = True

    if not wereThereAnyDepFiles:
        print("No Dep files found in "+path)

下面,该文件中写入的内容表明您希望这样做表明检查已结束,并且您再也找不到 .exe 文件。使用此假设,最好将语句放置在 if 块之外,如下所述。如果我误解了您的意图,请将语句放在 if 块中应该可以满足您的需求。

    with open(completeName, 'a') as ddr:
        ddr.write('No Further Dep Files found in'+path+'. \n')