Question

How to filter files (with known type) from os.walk?

I have list from os.walk. But I want to exclude some directories and files. I know how to do it with directories:

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

But how can I do it with files, which type I know. because this doesn't work:

if "*.dat" in files:
    files.remove("*.dat")
 45  71926  45
1 Jan 1970

Solution

 59
files = [ fi for fi in files if not fi.endswith(".dat") ]
2009-07-24

Solution

 33

Exclude multiple extensions.

files = [ file for file in files if not file.endswith( ('.dat','.tar') ) ]
2012-05-30