glob is a general term used to define techniques to match specified pattern according to rules related Unix shell. Linux and Unix systems and shells also supports glob and also provide function
glob() in system libraries. In this tutorial we will look
glob() function usage in Python programming language.
Import Glob Module
In order to use
glob() and related functions we need to import the
glob module. Keep in mind that
glob module contains
glob() and other related functions.
Exact String Search
We will start with a simple example. We will look how to match exact string or file name with a absolute path. In this example we will list file
/home/ismail/poftut.c . We can see example below that the function returns a list which contains matches.
Wildcard is important glob operator for glob operations. Wildcard or asterisk is used to match zero or more characters. Wildcard specified that there may be zero character or multiple character where character is not important. In this exmaple we will match files those have
As we can see that there are a lot of
.txt files those return in a Python list.
Wildcards with Multilevel Directories
We can use wildcards in order to specify multilevel directories. If we want to search one level down directories for specified glob we will use
/*/ . In this example we search for
.txt files in one level down directories in
Single Character Wildcard
There is a question mark which is used to match single character. This can be useful if we do not know single character for given name. In this example we will match files with files
file?.txt file where these will match
Glob also supports for alphabetic and numeric characters too. We can use
[ to start character range and
] is used to end character range. We can put whatever we want to match between square brackets. In this example we will match files and folders names those starts one of
In some cases we may want to match number range. We can use
- dash to specify start and end number. In this example we will match 0 to 9 with
0-9. In this example we will match file and folder names those contains numbers from 0 to 9 .
We can also define Alphabet ranges similar to number ranges. we will use
a-z for lowercase characters where
A-Z for uppercase characters. What if we need to match lower and uppercase characters in a single statement. We can use
a-Z to match both lower and uppercase letters. In this example we will match files and folder names those starts with letters between