我有一个类似下面给出的目录结构。
main folder
/ | \
folder1 folder2 folder3 ...
并且在所有这些文件夹中都有相同的文件data21.json
我的目标是在所有这些.json文件中搜索特定的字符串值(如' 0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'),如果在其中一个文件中找到,则只停止搜索,否则打印假。 我只能用这个
的一个文件来做这个 pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
found = False
if pipeline_id in open('dir1/data21.json').read():
found = True
pprint(found)
无法找到如何在所有/directory/anydirectory/data21.json中搜索
答案 0 :(得分:1)
我将详细阐述我的评论。此代码将遍历您main folder
中的所有项目,并检查您想要的内容。
pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
#list all the dirs inside the main folder
found = False
main_folder_path = "main_folder" #this will change depending from where you call your script
for dir_name in os.listdir(main_folder_path):
dir_path = main_folder_path+"/"+dir_name+"/data21.json"
if pipeline_id in open(dir_path).read():
found = True
break
pprint(found)
您可能还需要检查dir_name
是否是您想要的目录,或者如果您在main_folder
内混合它们,则需要检查文件。
答案 1 :(得分:0)
您也可以使用os.walk
-
import os
BASE_FOLDER = './main'
pipeline_id = '0d92c8d2-5a57-4c20-9ad7-cbe4fbf51615'
found = False
for r,d,f in os.walk(BASE_FOLDER):
for file_ in f:
if file_ == 'data21.json':
if pipeline_id in open(os.path.join(r, file_)).read():
found = True
break
if found:
break
print(found)