Skip to content
Fix Code Error

How to use glob() to find files recursively?

March 13, 2021 by Code Error
Posted By: Anonymous

This is what I have:

glob(os.path.join('src','*.c'))

but I want to search the subfolders of src. Something like this would work:

glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))

But this is obviously limited and clunky.

Solution

pathlib.Path.rglob

Use pathlib.Path.rglob from the the pathlib module, which was introduced in Python 3.5.

from pathlib import Path

for path in Path('src').rglob('*.c'):
    print(path.name)

If you don’t want to use pathlib, use can use glob.glob('**/*.c'), but don’t forget to pass in the recursive keyword parameter and it will use inordinate amount of time on large directories.

For cases where matching files beginning with a dot (.); like files in the current directory or hidden files on Unix based system, use the os.walk solution below.

os.walk

For older Python versions, use os.walk to recursively walk a directory and fnmatch.filter to match against a simple expression:

import fnmatch
import os

matches = []
for root, dirnames, filenames in os.walk('src'):
    for filename in fnmatch.filter(filenames, '*.c'):
        matches.append(os.path.join(root, filename))
Answered By: Anonymous

Related Articles

  • Taking an object's element and turning it into a…
  • Can't install via pip because of egg_info error
  • What are the undocumented features and limitations…
  • Form field border-radius is not working only on the…
  • Search match multiple values in single field in…
  • Transferring JavaScript objects to HTML table
  • How can I iterate over files in a given directory?
  • How to update other fields based on a field value in…
  • What's the difference between eval, exec, and compile?
  • Python is not calling fucntions properly
  • Calculate sum for group of dynamic table rows in jquery
  • Vue custom directive uses the updated Dom (or $el)
  • Relative imports for the billionth time
  • How do I merge two dictionaries in a single…
  • Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)
  • How can I search sub-folders using glob.glob module?
  • Python File Error: unpack requires a buffer of 16 bytes
  • Does the code after the recursion call get executed…
  • Python: importing a sub‑package or sub‑module
  • ExpressJS How to structure an application?
  • Search code inside a Github project
  • Incorporating vis.js into polymer-starter-kit version 1.2.3
  • What are type hints in Python 3.5?
  • Why does "polymer build" throw the error "File not…
  • How to get all of the immediate subdirectories in Python
  • What does if __name__ == "__main__": do?
  • How to make Lodash orderBy to sort only the records…
  • File changed listener in Java
  • Get parent of current directory from Python script
  • How to delete a file or folder?
  • How to update Python?
  • Usage of __slots__?
  • Extract a sorted list of a list by c#
  • How to declare an array inside MS SQL Server Stored…
  • How is Perl's @INC constructed? (aka What are all…
  • JS Graph recursive vs iterative DFS order difference
  • Ukkonen's suffix tree algorithm in plain English
  • Using recursion in a Vue component with JSON
  • What is your most productive shortcut with Vim?
  • Reference - What does this regex mean?
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Getting the closest string match
  • Pandas create the new columns based on the distinct…
  • Best way to sort through components Vue JS
  • SQL JOIN and different types of JOINs
  • What is the difference between re.search and re.match?
  • Does moment.js allow me to derive a timezone…
  • Install pip in docker
  • How to get the part of a file after the first line…
  • on input event not working on when using button value
  • SQL query return data from multiple tables
  • What does Ruby have that Python doesn't, and vice versa?
  • How to handle Vue 2 memory usage for large data (~50…
  • OpenCV Object detection with Feature Detection and…
  • Build the full path filename in Python
  • How to solve Internal Server Error in Next.Js?
  • Calculating the cumulative sum with a specific…
  • Why after set mapping, index return nothing?
  • Get a rows of number inside a textbox inside a table…
  • How to convert an XML file to nice pandas dataframe?
  • Smart way to truncate long strings
  • The definitive guide to form-based website authentication
  • How can I access and process nested objects, arrays or JSON?
  • What's the difference between Instant and LocalDateTime?
  • Keras Sequential API is replacing every layer with…
  • Multiple word search using trie in dart
  • What does the "yield" keyword do?
  • Text editor to open big (giant, huge, large) text files
  • What is it about Vue that enables developers to use…
  • Better way to sum a property value in an array
  • Importing a function from a class in another file?
  • Where and why do I have to put the "template" and…
  • numpy matrix vector multiplication
  • 3D Rotation of a camera using its own, new axes
  • Active tab issue on page load HTML
  • How not to get a repeated attribute of an object?
  • How do I ignore files in Subversion?
  • VueJS accessing data from component in root Vue instance
  • Is there a way with python to move files on windows…
  • How to get file creation & modification date/times…
  • Angular: Can't find Promise, Map, Set and Iterator
  • Expand Python Search Path to Other Source
  • How do I install PIL/Pillow for Python 3.6?
  • How can I update value in input type text on vue.js 2?
  • How to generate JAXB classes from XSD?
  • How to obtain the start time and end time of a day?
  • Accessing query values in Next.js
  • How to pass a decimal value when making a post…
  • How to sleep a process when using multiprocessing in…
  • Round number to nearest integer
  • How can I find the product GUID of an installed MSI setup?
  • How do I get the full path of the current file's directory?
  • Calling Python class method which is in another file
  • What is a NoReverseMatch error, and how do I fix it?
  • How do I create a search box like on…
  • Best way to bind textfield to a model in ember
  • Return row of Data Frame based on value in a column - R
  • What does "SyntaxError: Missing parentheses in call…
  • Are dictionaries ordered in Python 3.6+?
  • How to find out client ID of component for ajax…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Switch statement multiple cases in JavaScript

Next Post:

How to interpolate variables in strings in JavaScript, without concatenation?

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error