简体   繁体   English

在python中使用glob选择多个文件

[英]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. 我必须一次选择目录中的所有文件,文件名中间应包含y2001,y2002和y2003。 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 有关更多参考,请参见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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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