如何从os.walk过滤文件(已知类型)?

28 python

我有清单os.walk.但我想排除一些目录和文件.我知道如何使用目录:

for root, dirs, files in os.walk('C:/My_files/test'):
    if "Update" in dirs:
        dirs.remove("Update")
Run Code Online (Sandbox Code Playgroud)

但是我怎么能用我知道的文件来做呢.因为这不起作用:

if "*.dat" in files:
    files.remove("*.dat")
Run Code Online (Sandbox Code Playgroud)

gho*_*g74 33

files = [ fi for fi in files if not fi.endswith(".dat") ]
Run Code Online (Sandbox Code Playgroud)


oko*_*aka 17

排除多个扩展程序.

files = [ file for file in files if not file.endswith( ('.dat','.tar') ) ]
Run Code Online (Sandbox Code Playgroud)


run*_*uhl 7

还有一种方式,因为我刚刚写了这个,然后偶然发现了这个问题:

files = filter(lambda file: not file.endswith('.txt'), files)


Gle*_*ard 5

一种简洁的写作方式,如果你经常这样做:

def exclude_ext(ext):
    def compare(fn): return os.path.splitext(fn)[1] != ext
    return compare

files = filter(exclude_ext(".dat"), files)
Run Code Online (Sandbox Code Playgroud)

当然, exclude_ext 包含在您适当的实用程序包中。


Sil*_*ost 3

files = [file for file in files if os.path.splitext(file)[1] != '.dat']
Run Code Online (Sandbox Code Playgroud)