Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using-Python-Glob-Patterns

00:00 There are times when you just want one type of file or directory or perhaps all the items with a certain pattern of characters in their name. In this lesson, you’ll learn how to use Python glob patterns and about the many different glob patterns that you can take advantage of.

00:15 A method related to .rglob() is the glob() method. Both methods make use of glob patterns.

00:23 So what is a glob pattern? A glob pattern represents a collection of paths. Glob patterns make use of wildcard characters to match on certain criteria. For example, the single asterisk matches everything in the directory.

00:37 You probably remember this from the previous lesson. There are many different glob patterns you can take advantage of. Here are just a few common ones. So you have this list of files and folders, Notes.txt, todo.txt, 01.txt and Scripts, and you have the following glob pattern, *.txt.

00:58 Which of these files and folders matches

01:01 looking at the list? The two items that match are todo.txt and 01.txt. This is because the glob pattern *.txt matches files with any name ending in .txt.

01:15 You can try taking a look at another example. Looking at the same list of files and folders, and you have the glob pattern of six question marks.

01:23 Which of the files and folders match? The file 01.txt matches because the glob pattern with six question marks matches every item whose name is six characters long.

01:35 You can try taking a look at this last example, so you have the same list of files and folders and the glob pattern, capital N*, which folders and files match? The folder that matches is Notes.

01:50 This is because the glob pattern, capital N* matches every item that starts with the character capital N, so the folder Notes matches.

02:00 Now would be a good time to warn you that on Windows glob patterns are case insensitive because paths are case insensitive in general. On Unix-like systems, Linux and macOS, glob patterns are case sensitive.

02:15 With that in mind, we only covered a few of the many glob patterns available to you. Check out the documentation on fnmatch, which is the underlying module governing the behavior of glob to get a feel for the other patterns that you can use in Python.

02:30 In the next lesson, you’ll see glob patterns in action while you learn conditional listing using the glob() method.

Become a Member to join the conversation.