我有一个字符串列表,如果我的列表中的字符串出现在文件名中,那么我希望python打开该文件。问题是,我希望python按照字符串出现在我的列表中的顺序打开文件。我当前的代码按照python想要的顺序打开文件,只检查列表中的字符串是否出现在文件名中。
文件
dogs.html
cats.html
fish.html
蟒
list = ['fi', 'do', 'ca']
for name in glob.glob('*.html'):
for item in list:
if item in name:
with open(name) as k:
答案 0 :(得分:3)
lis = ['fi', 'do', 'ca']
for item in lis:
for name in glob.glob('*.html'):
if item in name:
with open(name) as k:
或首先创建所有文件的列表,然后在list
的每次迭代中过滤该列表:
>>> names=glob.glob('*.html')
>>> lis=['fi','do','ca']
>>> for item in lis:
... for name in filter(lambda x:item in x,names):
... with open('name') as k:
答案 1 :(得分:0)
您可以创建一组匹配项:
matching_glob = set([name for name in glob.glob('*.html')])
然后过滤您的列表
list_matching_glob = filter (lambda el: el in matching_glob) filter
答案 2 :(得分:0)
通过重复glob调用,你可以做得更简单:
names = ['fi', 'do', 'ca']
patterns = [s + "*.html" for s in names]
for pattern in patterns:
for fn in glob.glob(pattern):
with open(name) as k:
pass
如果您处理数千个文件,可以使用os.listdir和glob.fnmatch分解重复的文件系统访问权限。
答案 3 :(得分:0)
我会做这样的事情:
filenames = glob.glob('*.html')
for my_string in my_strings:
for fname in (filename for filename in filenames if my_string in filename):
with open(fname) as fobj:
#do something.