Even though the glob API is small, the module packs a lot of power. It is useful in any situation where a program needs to look for a list of files on the file system with names matching a pattern. To create a list of filenames that all have a certain extension, prefix, or any common string in the middle, use glob instead of writing custom code to scan the directory contents.

WildCast


In [1]:
import glob
for name in sorted(glob.glob('./*')):
    print(name)


./Path.ipynb
./glob.ipynb

In [10]:
import glob
print('Name explicitly:')
for name in sorted(glob.glob('/Users/*')):
    print(name)
print('Named with wildcard:')
for name in sorted(glob.glob('/Users/*/*')):
    print('  {}'.format(name))


Name explicitly:
/Users/Shared
/Users/gaufung
Named with wildcard:
  /Users/Shared/Apowersoft
  /Users/Shared/Paragon Software
  /Users/Shared/SC Info
  /Users/Shared/adi
  /Users/gaufung/Applications
  /Users/gaufung/Blog
  /Users/gaufung/Calibre Library
  /Users/gaufung/Desktop
  /Users/gaufung/Documents
  /Users/gaufung/Download
  /Users/gaufung/Downloads
  /Users/gaufung/FarBox
  /Users/gaufung/Library
  /Users/gaufung/Movies
  /Users/gaufung/Music
  /Users/gaufung/Pictures
  /Users/gaufung/Public
  /Users/gaufung/Resource
  /Users/gaufung/Software
  /Users/gaufung/WorkSpace
  /Users/gaufung/anaconda
  /Users/gaufung/blog_gaofeng
  /Users/gaufung/jupyter-tips-and-tricks
  /Users/gaufung/lua-5.3.0
  /Users/gaufung/lua-5.3.0.tar.gz
  /Users/gaufung/nltk_data
  /Users/gaufung/scikit_learn_data
  /Users/gaufung/statsmodels_data