Reading Time: 1 minutes
Finding pathnames matching a Unix-style pattern in Python
The glob standard library helps to find pathnames matching a Unix-style pattern, using its glob() function. You can use Unix wildcards such as *, ? and character ranges with [ ].
# Directory structure of sample Folder |
│ 1ab .txt |
│ a2.txt |
│ a2b.txt |
│ abc.txt |
│ def .txt |
│ picture.jpg |
│ python.py |
│ word.docx |
└───dir1 |
file1underDir1.txt |
>>> import glob |
# The * denotes one or more characters |
>>> glob.glob( '*.txt' ) # matches files with extension 'txt' |
[ '1ab.txt' , 'a2.txt' , 'a2b.txt' , 'abc.txt' , 'def.txt' ] |
>>> glob.glob( '*.doc*' ) # matches files with extension having the string 'doc' in it. |
[ 'word.docx' ] |
# The ? denotes a single character |
>>> glob.glob( '??.txt' ) # matches text files with only two letters in its name. |
[ 'a2.txt' ] |
# [character-range] matches any character lying in the said range. |
>>> glob.glob( '[a-z][0-9].txt' ) # matches two-character named text files with an alphabetic first character & numeric second character. |
[ 'a2.txt' ] |
>>> glob.glob( '[a-z][0-9][a-z].txt' ) # matches three-character named text files with an alphabetic first character, numeric second character & an alphabetic third character. |
[ 'a2b.txt' ] |
# The '**' pattern matches any file, directory or subdirectory. |
>>> glob.glob( '**' ) |
[ '1ab.txt' , 'a2.txt' , 'a2b.txt' , 'abc.txt' , 'def.txt' , 'dir1' , 'picture.jpg' , 'python.py' , 'word.docx' ] |