0

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')
1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

thanks btw how to feed them separately y2001, y2002, y2003 . looking for alternative..
@viena There's no need to feed them separately.
@ Ashwini Chaudhary please give me alternative like y2001 and y2002 and y2003
@viena Use a list comprehension on os.listdir and filter the list items using either substring match or regex.
@viena then consider using fnmatch.fnmatch in a loop (if you are not satisfied with regex): docs.python.org/2/library/fnmatch.html#fnmatch.fnmatch
2

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']

Comments

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.