In this section, we will learn about pattern matching for files and directories. Python has the glob module, which is used to find the names of files and directories that match specific patterns.
Now, we will look at an example. First, create a pattern_match.py script and write the following content in it:
import glob
file_match = glob.glob('*.txt')
print(file_match)
file_match = glob.glob('[0-9].txt')
print(file_match)
file_match = glob.glob('**/*.txt', recursive=True)
print(file_match)
file_match = glob.glob('**/', recursive=True)
print(file_match)
Run the script as follows:
$ python3 pattern_match.py
Output:
['file1.txt', 'filea.txt', 'fileb.txt', 'file2.txt', '2.txt', '1.txt', 'file.txt']
['2.txt', '1.txt']
['file1...