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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Scaling InfluxDB for High-Volume Reporting With Continuous Queries (CQs)
  • Streamlining Event Data in Event-Driven Ansible
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  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 user avatar
Jay Sridhar
·
Jun. 17, 17 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
179.0K Views

Join the DZone community and get the full member experience.

Join For Free

“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, DZone MVB. 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
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!