• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Code Snippets / OS.Walk and Fnmatch in Python

OS.Walk and Fnmatch in Python

Author: PFB Staff Writer
Last Updated: December 2, 2020

Overview

In an earlier post, OS.walk in Python, I described how to use os.walk and showed some examples on how to use it in scripts.

In this article, I will show how to use the os.walk() module function to walk a directory tree, and the fnmatch module for matching file names.

What is OS.walk?

It generates the file names in a directory tree by walking the tree either top-down or bottom-up.

For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).

dirpath # is a string, the path to the directory.

dirnames # is a list of the names of the subdirectories in dirpath (excluding ‘.’ and ‘..’).

filenames # is a list of the names of the non-directory files in dirpath.

Note that the names in the lists contain no path components.

To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). For more information, please see the Python Docs.

What is Fnmatch

The fnmatch module compares file names against glob-style patterns such as used by Unix shells.

These are not the same as the more sophisticated regular expression rules. It’s purely a string matching operation.

If you find it more convenient to use a different pattern style, for example regular expressions, then simply use regex operations to match your filenames. http://www.doughellmann.com/PyMOTW/fnmatch/

What does it do?

The fnmatch module is used for the wild-card pattern matching.

Simple Matching

fnmatch() compares a single file name against a pattern and returns a boolean indicating whether or not they match. The comparison is case-sensitive when the operating system uses a case-sensitive file system.

Filtering

To test a sequence of filenames, you can use filter(). It returns a list of the names that match the pattern argument.

Find all mp3 files

This script will search for *.mp3 files from the rootPath (“/”)


import fnmatch
import os
 
rootPath = '/'
pattern = '*.mp3'
 
for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        print( os.path.join(root, filename))

Search computer for specific files

This script uses ‘os.walk’ and ‘fnmatch’ with filters to search the hard-drive for all image files

import fnmatch
import os

images = ['*.jpg', '*.jpeg', '*.png', '*.tif', '*.tiff']
matches = []

for root, dirnames, filenames in os.walk("C:\"):
    for extensions in images:
        for filename in fnmatch.filter(filenames, extensions):
            matches.append(os.path.join(root, filename))

There are many other (and faster) ways to do this, but now you understand the basics of it.

More Reading

http://rosettacode.org/wiki/Walk_a_directory/Recursively#Python

Stackoverflow Match Pattern

Stackoverflow oswalk with fnmatch

osWalk In Python

Having Fun With osWalk

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Code Snippets, fnmatch, Modules Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary โ€“ How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 ยท PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us