Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

People also ask

How do you filter a file type in Python?

To filter and list files according to their names with Pathlib Python Module, we need to use the “glob()” function. “glob()” function is being used for determining patterns to filter the files according to their names or extension.

What is the difference between OS Listdir () and OS walk?

listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

What does OS Walk () do?

OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

Does OS walk Change directory?

walk() never changes the current directory, and assumes that its caller doesn't either.


files = [ fi for fi in files if not fi.endswith(".dat") ]

Exclude multiple extensions.

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

And in one more way, because I just wrote this, and then stumbled upon this question:

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

Mote that in python3 filter returns a generator, not a list, and the list comprehension is "preferred".


A concise way of writing it, if you do this a lot:

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

files = filter(exclude_ext(".dat"), files)

Of course, exclude_ext goes in your appropriate utility package.


files = [file for file in files if os.path.splitext(file)[1] != '.dat']