Python删除文件夹下所有包含指定字符串的文件

版权声明:转载注明出处 https://blog.csdn.net/york1996/article/details/83003439

如果是几万张照片,即使是框选再删除也会很慢,这个时候不如用python来删除文件。需要导入自带的os模块。

下面是代码:

import os
path="E:/DataSets/catdog/"
files=os.listdir(path)
for i ,f in enumerate(files):
    if f.find("cat")>=0 :
        print(i)
        os.remove(path+f)

其中的find函数如果找到字符串会返回字符串所在的位置,找不到参数中指定的字符串返回-1。

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,
such that sub is contained within S[start:end].  Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.

猜你喜欢

转载自blog.csdn.net/york1996/article/details/83003439