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))
3
  • 1
    Python is misspelled in the post title :-) Commented Apr 20, 2017 at 6:26
  • Embarrassing - but good catch Commented Apr 20, 2017 at 6:33
  • don't worry, I was in "debug mode" ;-) Commented Apr 20, 2017 at 7:10

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

1 Comment

I was close I see. I think yours is very general though (+1)
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']

5 Comments

Oh I completely missed basename
However, this solution will also fetch files like filepat.txt.bak
To fix that, just use i.endswith('pat.txt')
@WiktorStribiżew , we can still achieve this using endswith('pat.txt') if required :)
- Yes, but then it would fail to fetch FILEPAT.TXT. - We may use lower().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.