Pattern matching files and directories

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.txt', 'filea.txt', 'fileb.txt', 'file2.txt', '2.txt', '1.txt', 'file.txt', 'dir1/3.txt', 'dir1/4.txt']
['dir1/']

In the previous example, we used Python's glob module for pattern matching. glob (pathname) will return the list of names that matches with the pathname. In out script, we have passed three pathnames in three different glob() functions. In the first glob(), we passed the pathname as *.txt; this will return all the filenames with .txt extensions. In the second glob(), we passed [0-9].txt; this will return filenames that start with a digit. In the third glob(), we passed **/*.txt, which will return filenames as well as directory names. It will also return the filenames from those directories. In the fourth glob(), we passed **/, which will return directory names only.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset