Reputation: 4499
I have to select all the files in a directory at a time which has y2001, y2002, and y2003 in the mid of filename. How can I?
import glob
files = glob.glob('*y2001*.jpg')
Upvotes: 0
Views: 2047
Reputation: 43497
Here is an overkill method for solving your problem.
import os
import re
import functools
def validate_file(validators, file_path):
return any(re.search(validator, file_path) for validator in validators)
def get_matching_files_in_dir(directory, validator, append_dir=True):
for file_path in os.listdir(directory):
if validator(file_path):
yield os.path.join(directory, file_path) if append_dir else file_path
# define your needs:
matching_patterns = ['y2001', 'y2002', 'y2003']
validator = functools.partial(validate_file, matching_patterns)
# usage
list(get_matching_files_in_dir('YOUR DIR', validator))
An Example:
>>> matching_patterns = ['README']
>>> validator = functools.partial(validate_file, matching_patterns)
>>> print list(get_matching_files_in_dir('C:\\python27', validator))
['C:\\python27\\README.txt']
Upvotes: 2
Reputation: 3970
You can do it with
import glob
files = glob.glob('*y200[123]*.jpg')
for futher reference see http://docs.python.org/2/library/glob.html
Upvotes: 2