python - 在循环中查找具有特定单词的文件?
问题描述
在该文件夹中有名为: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
.
解决方案
我认为(工作)的想法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'}
)。
推荐阅读
- c++ - 以编程方式测量Linux中带宽的正确方法
- r - 在 R 中为 Keras 丢失了 numpy
- python - 如何使用字节访问字符串?
- r - 为什么使用 R 包鼠标在插补过程中显示错误消息?错误消息:$ 运算符对原子向量无效
- php - 如何在托管服务提供商的服务器上存储敏感信息?
- c++ - 为什么在 glfw 窗口上没有使用 opengl 显示位图图像?在 C++ 中读取位图图像文件时出现问题
- azure-devops - 如何在 azure devops 中为工作项状态添加新的自定义类别?
- javascript - 在首发主题shopify的购物车页面中添加为数量下拉列表
- java - 无法在 Android Studio 中发送消息
- android - 这个颤振代码不起作用有什么原因吗?