简体   繁体   中英

select multiple files using glob in python

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM