The glob
module in Python allows you to retrieve files or directories that match a specific pattern. If you want to exclude certain files or directories from your search, you can use the glob
function’s exclusion patterns.
Examples:
import glob
# Retrieve all files excluding ".txt" files in the current directory
files = glob.glob('*.[!t][!x][!t]')
print(files)
# Retrieve all directories excluding "test_" prefixed directories
directories = glob.glob('[!t][!e][!s][!t]_*')
print(directories)
In the examples above, we are using the glob.glob
function to search for files and directories based on exclusion patterns:
-
The first example retrieves all files excluding those with a
.txt
extension. The exclusion pattern*.[!t][!x][!t]
matches any file name that does not end with.txt
. -
The second example retrieves all directories excluding those that start with
test_
. The exclusion pattern[!t][!e][!s][!t]_*
matches any directory name that does not start withtest_
.
It’s important to note that the exclusion patterns use square brackets. Each character inside the brackets represents a potential match for that position. By using a negation operator !
before each character, we exclude specific possibilities from the match. Multiple negation operators allow us to define more complex exclusion patterns.