Listing a Directory With Python

Learn how to list contents of a directory from python. Also, easily find and process files matching conditions from your python program.

“If at first you don’t succeed, destroy all evidence that you tried.”
― Steven Wright

1. Introduction

There are several methods to list a directory in python. In this article we present a few of these along with the caveats for each.

2. Listing Files in a Directory

The simplest way to get a list of entries in a directory is to use os.listdir(). Pass in the directory for which you need the entries; use a “.” for the current directory of the process.

for x in os.listdir('.'):
    print x

# prints
LICENSE
index.js
API.md
ISSUE_TEMPLATE.md
package.json
test
...

As you can see, the function returns a list of directory entry strings with no indication of whether it is a file, directory, etc. Also, ‘.’ and ‘..’ entries are not returned from the call.

If you need to identify whether the entry is a file, directory, etc, you can use os.path.isfile() as shown.

for x in os.listdir('.'):
    if os.path.isfile(x): print 'f-', x
    elif os.path.isdir(x): print 'd-', x
    elif os.path.islink(x): print 'l-', x
    else: print '---', x

# prints
f- LICENSE
f- index.js
f- API.md
f- ISSUE_TEMPLATE.md
f- package.json
d- test
f- .gitignore
d- .git
f- rollup.config.js
...

Here is a one-liner using filter() to collect the files:

print filter(lambda x: os.path.isfile(x), os.listdir('.'))

# prints
['LICENSE', 'index.js', 'API.md', 'ISSUE_TEMPLATE.md', 'package.json', '.gitignore', ...]

Or the directories:

print filter(lambda x: os.path.isdir(x), os.listdir('.'))

# prints
['test', '.git', 'img']

3. Finding Files – Current Directory Only

Here is a simple one-liner to find javascript files in a directory. Note that this does NOT descend the directory hierarchy but just returns the matching entries in the specified directory (See below for a recipe which does that):

print filter(lambda x: x.endswith('.js'), os.listdir('d3'))

# prints
['index.js', 'rollup.config.js', 'rollup.node.js']

Using list comprehension, the above can also be written:

print [x for x in os.listdir('.') if x.endswith('.js')]

# prints
['index.js', 'rollup.config.js', 'rollup.node.js']

Match multiple file extensions using a regular expression.

import re
rx = re.compile(r'\.(js|md)')
print filter(rx.search, os.listdir('.'))

# prints
['index.js', 'API.md', 'ISSUE_TEMPLATE.md', 'package.json', 'rollup.config.js', ...]

Again, using list comprehension the above can be re-written as follows:

print [x for x in os.listdir('.') if rx.search(x)]

# prints
['index.js', 'API.md', 'ISSUE_TEMPLATE.md', 'package.json', 'rollup.config.js', 'CHANGES.md', 'README.md', 'rollup.node.js']

4. Recursive Descent – Using os.walk()

The function os.walk() provides a way of listing all entries starting from a directory – including entries in the sub-directories. The function returns a generator which, on each invocation, returns a tuple of current directory name, list of directories in that directory and a list of files. Here is an example:

for x in os.walk('.'):
    print x

# prints
('.', ['test', '.git', 'img'], ['LICENSE', 'index.js', 'API.md', 'ISSUE_TEMPLATE.md', 'package.json', '.gitignore', 'rollup.config.js', 'CHANGES.md', 'd3.sublime-project', 'README.md', 'rollup.node.js', '.npmignore'])
('./test', [], ['test-exports.js', 'd3-test.js'])
('./.git', ['objects', 'logs', 'info', 'refs', 'hooks', 'branches'], ['packed-refs', 'HEAD', 'description', 'config', 'index'])
('./.git/objects', ['pack', 'info'], [])
...

5. Recursive File Find

Here is one implementation of recursively finding files matching the pattern r'\.(js|md)' starting from the current directory.

rx = re.compile(r'\.(js|md)')
r = []
for path, dnames, fnames in os.walk('.'):
    r.extend([os.path.join(path, x) for x in fnames if rx.search(x)])
print r

# prints
['./index.js', './API.md', './ISSUE_TEMPLATE.md', './package.json', './rollup.config.js', './CHANGES.md', './README.md', './rollup.node.js', './test/test-exports.js', './test/d3-test.js']

And here is how you can find files larger than 10000 bytes in the hierarchy.

r = []
for path, dnames, fnames in os.walk('.'):
    r.extend([os.path.join(path, x) for x in fnames if os.path.getsize(os.path.join(path, x)) > 10000])
print r

How about a list of files that have been modified less than 8 hours ago?

r = []
now = int(time.time())
for path, dnames, fnames in os.walk('.'):
    r.extend([os.path.join(path, x) for x in fnames if (now - int(os.path.getmtime(os.path.join(path, x))))/(60*60) < 8])
print r

As you can see, it is possible to write various conditions for selecting files and that makes this method more powerful than the shell for finding files.

Conclusion

In this article, we learn how to list the contents of a directory from python. It is also easy to apply conditions for selecting files using the standard python constructs such as filter() and list comprehension. Finally, we saw how to process an entire directory hierarchy using os.walk(), including writing conditions for finding files.

Leave a Reply

Your email address will not be published. Required fields are marked *