PP3E\Examples\PP3E\Lang\summer-alt.py
PP3E\Examples\PP3E\Lang\summer.py
PP3E\Examples\PP3E\PyTools\search_all.py
Here, we get back filenames from two different directories that match the s.py pattern;
because the directory name preceding this is a wildcard, Python collects all possible
ways to reach the base filenames. Using os.popen to spawn shell commands achieves
the same effect, but only if the underlying shell or listing command does, too, and with
possibly different result formats across tools and platforms.
The os.listdir call
The os module’s listdir call provides yet another way to collect filenames in a Python
list. It takes a simple directory name string, not a filename pattern, and returns a list
containing the names of all entries in that directory—both simple files and nested
directories—for use in the calling script:
>>> import os
>>> os.listdir('.')
['parts', 'PP3E', 'random.bin', 'spam.txt', 'temp.bin', 'temp.txt']
>>>
>>> os.listdir(os.curdir)
['parts', 'PP3E', 'random.bin', 'spam.txt', 'temp.bin', 'temp.txt']
>>>
>>> os.listdir('parts')
['part0001', 'part0002', 'part0003', 'part0004']
This, too, is done without resorting to shell commands and so is both fast and portable
to all major Python platforms. The result is not in any particular order across platforms
(but can be sorted with the list sort method or sorted built-in function); returns base
filenames without their directory path prefixes; does not include names “.” or “..” if
present; and includes names of both files and directories at the listed level.
To compare all three listing techniques, let’s run them here side by side on an explicit
directory. They differ in some ways but are mostly just variations on a theme for this
task—os.popen returns end-of-lines and may sort filenames on some platforms,
glob.glob accepts a pattern and returns filenames with directory prefixes, and os.list
dir takes a simple directory name and returns names without directory prefixes:
>>> os.popen('dir /b parts').readlines()
['part0001\n', 'part0002\n', 'part0003\n', 'part0004\n']
>>> glob.glob(r'parts\*')
['parts\\part0001', 'parts\\part0002', 'parts\\part0003', 'parts\\part0004']
>>> os.listdir('parts')
['part0001', 'part0002', 'part0003', 'part0004']
Of these three, glob and listdir are generally better options if you care about script
portability and result uniformity, and listdir seems fastest in recent Python releases
(but gauge its performance yourself—implementations may change over time).
Directory Tools | 167