首页 > 解决方案 > 在循环中查找具有特定单词的文件?

问题描述

在该文件夹中有名为:a11.shp,a11.shx,u21.shp,u21.shx

import os 
words = ('a11','u21')
for root, dirs,files in os.walk(r'C:\Users\user\Desktop\folder1'):
    for i in files: 
        if i in words:
            print(i)

TypeError:元组索引必须是整数或切片,而不是 str

它需要某种索引才能为所有项目运行元组。

我想将它用作“包含”该词,但它不像包含in我想将它用作“包含”该词,但在这种情况下

在元组中给出这些确切的单词时如何做到这一点。没有startswith.

标签: python

解决方案


我认为(工作)的想法if words in i:if any(w in i for w in words),但它匹配子字符串(不是确切的字符串)并且不是很快。

你必须反过来做。测试file_without_extension in words

例如像这样:

for i in files: 
    # check if the filename (without extension) is in "words" iterable
    if os.path.splitext(i)[0] in words:
        print(i)

如果您有很多“单词”,请使用 aset而不是 atuple以加快查找速度 ( words = {'a11','u21'})。


推荐阅读