Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all files in current directory with filenames that match a certain pattern in python?

Tags:

python

I am trying to find all the files in the same directory as my script that has a filename matching a certain pattern. Ideally, I would like to store it in an array once I get them. The pattern I need to match is something like: testing.JUNK.08-05.txt. All the filenames have the testing in the front and end with the date (08-05.txt). The only difference is the JUNK in the middle which can include any valid characters.

What would be the most efficient way to do this? I can be working with anywhere from 1 to thousands of files?

Additional things to note: Using python 2.6 and I need this to work on Unix-based operating systems.

like image 563
bobby_mansono Avatar asked Aug 05 '10 18:08

bobby_mansono


People also ask

What does glob glob () do in Python?

glob (short for global) is used to return all file paths that match a specific pattern. We can use glob to search for a specific file pattern, or perhaps more usefully, search for files where the filename matches a certain pattern by using wildcard characters.


1 Answers

Use the glob module:

import glob
for name in glob.glob('testing*08-05.txt'):
    print name
like image 77
Lukáš Lalinský Avatar answered Sep 28 '22 08:09

Lukáš Lalinský