Find specific files in subdirs using Python os.walk
<p>In Windows, if I ran:</p>

<p>dir NP_???.LAS</p>

<p>I get 2 files:</p>

<p>NP_123.LAS</p>

<p>NP_1234.LAS</p>

<p>Using fmatch with NP_????.LAS mask I get only NP_1234.LAS, not NP_123.LAS.</p>

<p>Below, the code IÂ´m running:</p>

<pre><code>def FindFiles(directory, pattern):
    flist=[]
    for root, dirs, files in os.walk(directory):
        for filename in fnmatch.filter(files, pattern):
            flist.append(os.path.join(root, filename))
    return flist
</code></pre>

<p>ItÂ´s possible to change this to get the same file list as dir command, using only one pattern?</p>

<p>You could use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">re</a> to give you more flexibility by allowing actual regular expressions. The regular expression "[0-9]{3,4}" matches either 3 or 4 digit numbers. </p>

<pre><code>def FindFiles(directory, pattern):
    flist=[]
    for root, dirs, files in os.walk(directory):
        prog = re.compile("NP_[0-9]{3,4}.txt")
        for filename in filter(prog.match, files):
            flist.append(os.path.join(root, filename))
    return flist
</code></pre>

python os.walk