Glob

Sometimes you don't want to list all files in a directory but just a specific set, like all .txt files one directory deep. That’s where the glob  module comes in. 

What is glob ? The glob module is a built-in Python package used to find files and paths that match a specific Unix-style pattern. It returns a list of matching file paths.

The most useful function in the glob module is also called glob() , so you’ll often write:

import glob
f = glob.glob('*/*.TXT')
print(f)

Which would return an output likely similar to the following: 

['FOLDER\\note.TXT', 'FOLDER\\world.TXT']
  • The example above looks for files in the current directory that matches the pattern you specify, here it's '*/*.TXT'.
  • * means match anything.
  • 'FOLDER/*.TXT' means: In the FOLDER directory, find all files that end in .TXT .
  • It only looks one directory deep, it won't recursively search sub-folders unless you use ** with the recursive=True argument.

Tip: If you are doing data analysis, and you have a good naming scheme for your files, this is a great way to list a whole list of data files, without picking up other files.

★ Knowledge Check
You have completed 0% of the lesson
0%