DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions
  • Building a Flask Web Application With Docker: A Step-by-Step Guide
  • Packaging Python Classes as a Wheel
  • Implementing ROS Communication Patterns

Trending

  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software
  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • YAGNI in the Age of AI Coding
  • How to Migrate From LangChainGo to Genkit Go

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Listing a Directory With Python

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. Cool, huh?

By 
Jay Sridhar
·
Jun. 17, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
179.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

“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


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


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('.'))


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

Or the directories:

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


['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'))


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

Using list comprehension, the above can also be written as follows:

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


['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('.'))


['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)]


['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 the current directory name, a list of directories in that directory, and a list of files. Here is an example:

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


('.', ['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


['./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 learned 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.

Directory Listing (computer) Python (language)

Published at DZone with permission of Jay Sridhar. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Managing AWS Managed Microsoft Active Directory Objects With AWS Lambda Functions
  • Building a Flask Web Application With Docker: A Step-by-Step Guide
  • Packaging Python Classes as a Wheel
  • Implementing ROS Communication Patterns

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook