我有一個愚蠢的問題。所以基本上,有很多 JSON 檔案,例如,我只需要找到只包含我現在需要的資訊的 JSON 檔案,并列印那些包含我需要的資訊的檔案名?
所以有一個例子:我有一個檔案所在的目錄,這是 JSON 檔案包含的資訊
{
"version": "1.0.4",
"room": {
"index": 2,
"label": "Bedroom",
"score": 0.999368429,
"threshold": 0.6,
"raw": {
"Balcony": {
"index": 0,
"score": 0.000324130058
},
"Bathroom": {
"index": 1,
"score": 8.77380371e-05
},
"Bedroom": {
"index": 2,
"score": 0.999368429
},
"Dining Room": {
"index": 3,
"score": 0.000696450472
},
"Garage": {
"index": 4,
"score": 0.000141739845
},
"Hallway": {
"index": 5,
"score": 3.37660313e-05
},
"Kitchen": {
"index": 6,
"score": 4.11570072e-05
},
"Laundry Room": {
"index": 7,
"score": 9.4473362e-06
}
,...
}
}
}
現在我需要找到所有包含"label": "Bedroom" 并列印這些檔案名的JSON 檔案。它只適合我。我在學。提前致謝。
uj5u.com熱心網友回復:
嘗試這個
import glob
import json
file_dir = 'wkdir1/' #file location
files = glob.glob(file_dir '*.json')
key = 'Bedroom'
files_with_key = []
for fl in files:
f = open(fl)
json_data = json.load(f)
if key == json_data['room']['label']:
files_with_key.append(fl)
print(files_with_key)
uj5u.com熱心網友回復:
您可以遍歷當前目錄中的檔案并檢查它是否包含您需要的資訊。
import os
# The directory that you want to search in. Let's assume that it is named "data"
DIR = "data"
data = "" # The data to check against. I'm not going to write that here, as it is too long.
for file in os.listdir(DIR):
with open(file, "r") as f:
if f.readlines() == data:
print(file)
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366630.html
上一篇:無效的狀態機定義
