The Glob module of the Python standard library supports querying files or directories that match a specified pattern. The pattern used here is not a regular expression, but rather a wildcard that matches the Unix-style pathname extension.
Supported wildcard characters:
Wildcard characters |
Description |
* |
Match any of the characters |
? |
Match one character |
[] |
Match any of the characters between parentheses, which you can use-to represent a range |
\ |
Escape character, such as with \? The? |
Suppose you now have a directory named Dir, and the structure of the directory and its subdirectories is as follows:
├──dir│├──db.conf│├──dir1││├──hello-a.xml││├──hello-b.xml││└──hello-d.xml│├──dir2││ ├──2014││└──2015││ ├──01.log││ ├──02.log││ └──03.log│├──f1.txt│├──f2.txt│ ├──f3.txt│├──foo.txt│└──log.conf├──hello.py
glob_demo.py
ImportGlobPrintGlob.glob ('dir/*')#[' Dir/f2.txt ', ' dir/dir2 ', ' dir/f3.txt ', ' dir/f1.txt ', ' dir/foo.txt ', ' dir/dir1 ', ' dir/db.conf ', ' dir/log.conf '] PrintGlob.glob ('Dir/dir1/hello-[a-c].xml')#[' Dir/dir1/hello-b.xml ', ' dir/dir1/hello-a.xml ']PrintGlob.glob ('Dir/dir2/*/[0-9]*.log')#[' Dir/dir2/2015/03.log ', ' dir/dir2/2015/01.log ', ' Dir/dir2/2015/02.log ']PrintGlob.glob ('dir/f?. TXT')#[' Dir/f2.txt ', ' dir/f3.txt ', ' dir/f1.txt ']PrintGlob.glob ('dir/*.conf')#[' dir/db.conf ', ' dir/log.conf ']
Python (2.7.6) glob-Files matching a specified pattern