我必须在文件名中间选择y2001,y2002和y2003的目录中的所有文件。我怎么能够?
import glob
files = glob.glob('*y2001*.jpg')
答案 0 :(得分:2)
你可以用
完成import glob
files = glob.glob('*y200[123]*.jpg')
答案 1 :(得分:2)
这是解决问题的过度杀伤方法。
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))
一个例子:
>>> matching_patterns = ['README']
>>> validator = functools.partial(validate_file, matching_patterns)
>>> print list(get_matching_files_in_dir('C:\\python27', validator))
['C:\\python27\\README.txt']