Tip 28 glob() the Files

Pythonic Programming — by Dmitry Zinoviev (37 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Discover All Characters in One Place | TOC | Use Strings as Files 👉

★2.7, 3.4+ Anyone who works with the shell command line knows how easy it is to get a listing of all files or the files whose names match some pattern. For example, this is how you get the names of all files that contain seven characters and the extension pml:

​ ​/home/dzpythonic>​​ ​​ls​​ ​​???????.pml​
​ Changes.pml General.pml Preface.pml

You wish it were equally easy in Python. As a matter of fact, it is, thanks to the module glob. The namesake function takes the pattern as a string and returns a list of all matching filenames. You can use the “standard” shell-style wildcards like ? (matches any single character) and * (matches any number of characters):

​ glob.glob(​"???????.pml"​)​=> ​['Changes.pml', 'General.pml', 'Preface.pml']​

Function glob.glob is even more potent than the shell globbing mechanism. When you call it with the pattern “**” and the optional parameter recursive=True, it returns the complete list of files and directories in the current directory and all of its subdirectories.

👈 Discover All Characters in One Place | TOC | Use Strings as Files 👉

Pythonic Programming by Dmitry Zinoviev can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.