Fix Python – glob exclude pattern

Question

Asked By – Anastasios Andronidis

I have a directory with a bunch of files inside: eee2314, asd3442 … and eph.

I want to exclude all files that start with eph with the glob function.

How can I do it?

Now we will see solution for issue: glob exclude pattern


Answer

The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from pymotw: glob – Filename pattern matching].

So you can exclude some files with patterns.
For example to exclude manifests files (files starting with _) with glob, you can use:

files = glob.glob('files_path/[!_]*')

This question is answered By – Kenly

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0