How to recursively find files using Glob()?

Asked 2 years ago, Updated 2 years ago, 114 views

I want to use Glob() to recursively find the file.

The code I use is Glob(os.path.join('src','*.c')) This code is currently in the src directory only.Locate the c file. Also in the subdirectory of src How do I find the c file?

I'm temporarily using the source code below, but it's not like Python I want to get help from other people because the code looks messy.

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

python path glob

2022-09-22 15:13

1 Answers

On the Python 3.5 sub-phase, the glob module supports "**" directives.

Therefore, if you have a question, you can write it as follows.

import glob

for filename in glob.iglob('src/**/*.c', recursive=True):
    print(filename)

If you need a list rather than a print, glob of the above code.iglob is glob.Please change to glove

In older versions, os.walk is used to recursively scan directories Write fnmatch.filter when examining file names.

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

In Python 2.1 and below, fnmatch.filter in the code from 2.2 to 3.4.You need to change it to glob.


2022-09-22 15:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.