【发布时间】:2021-04-01 15:03:06
【问题描述】:
我有一个包含文件的字典:
files = {
"/test/path/file1.c": "NotImportant",
"/test/path/file2.c": "NotImportant",
"/other/path/filex.c": "NotImportant",
"/different/path/filez.c": "NotImportant"
}
我现在有一个字典,例如path = '/test/path/' 我想看看哪个文件在这个特定的路径中。
我试过了
if path in files:
print("found")
但是这对我不起作用。我通过遍历每个文件并使用相同的语句进行检查来解决它。还有其他方法可以解决吗?
我的解决方案:
for file in files:
if path in file:
print("found")
为什么该语句在这里有效,而不是以前?我想要一个更好的解决方案,而不是遍历整个文件。
【问题讨论】:
-
您拥有的“字典”实际上都不是字典。第一个是一个集合(但缺少逗号),第二个是一个字符串
-
只是为了演示(不应该是实现),所以你知道我的意思。我仍在使用字典。
-
请参阅How to Ask 并提供minimal reproducible example。我们不明白你的意思,你必须给我们看
-
第一个语句不起作用,因为您在文件集中寻找
'/test/path/',而在第二个语句中,您正在寻找文件集中的对象。 -
如何检查给定路径中的文件。那是我的问题
标签: python dictionary directory path