3

If one want to get the (absolute) file paths (file listings) of all files with names of certain pattern how can this be done in Python (v 3.5 on unix). Something similar to the bash command find -regex 'pattern'. I have been looking as the os, glob, os.path and this SO but cannot get it together.

Say you want absolute paths to the files that matches /.*[pat.txt]$/ and you have the below diretories:

/home/me/dir1/dir1a/filepat.txt #1
/home/me/dir1/dir1a/file.txt
/home/me/dir1/dir1a/filepat.png
/home/me/dir2/filepat.txt #2
/home/me/dir3/dir3a/dir3ab/filepat
/home/me/dir3/dir3a/dir3ac/filepat.txt #3 
/home/me/dir3/dir3a/dir3ac/filepat.png

Then you would get want the three indicated paths:

/home/me/dir1/dir1a/filepat.txt
/home/me/dir2/filepat.txt
/home/me/dir3/dir3a/dir3ac/filepat.txt

One try was:

import fnmatch
import os 
start_path = "/home/me/" 
for root, dirs, files in os.walk(start_path):
    for filename in fnmatch.filter(files, ".*pat.txt"):
        print(os.path.join(start_path, filename))
Community
  • 1
  • 1
user3375672
  • 3,728
  • 9
  • 41
  • 70

2 Answers2

3

Here is one using regexes, but for the simple case I would go with akash`s answer using in operator

import re
pattern = re.compile(r'.*pat\.txt$')

import fnmatch
import os 
start_path = "/home/me/" 
for root, dirs, files in os.walk(start_path):
    for filename in files:
        if pattern.find(filename):
            print(os.path.join(start_path, filename))
redacted
  • 3,789
  • 6
  • 25
  • 38
1

You can use basename and in operator

x = given list
>>> [i for i in x if 'pat.txt' in os.path.basename(i)]
['/home/me/dir1/dir1a/filepat.txt',
 '/home/me/dir2/filepat.txt',
 '/home/me/dir3/dir3a/dir3ac/filepat.txt']
akash karothiya
  • 5,736
  • 1
  • 19
  • 29