我有一個這樣的json物件檔案
dict\n
dict\n
.
.
.
這就是我制作這個檔案的方式
with open(old_surveys.json, 'a ') as f1:
for survey in data:
surv = {"sid": survey["id"],
"svy_ttl": survey["title"]),
"svy_link": survey["href"]
}
f1.seek(0)
if str(surv["sid"]) not in f1.read():
json.dump(surv, f1)
f1.write('\n')
f1.close()
現在我想檢查檔案中是否有特定的字典old_surveys.json。如何逐行閱讀?
uj5u.com熱心網友回復:
為了以更有效的方式避免重復,并回答您的問題:
import json
with open('old_surveys.json', 'a ') as f1:
# first load all the old surveys in a dictionary
f1.seek(0)
surveys = {}
for line in f1:
d = json.loads(line)
surveys[d['sid']] = d
# then write any new ones from data
for survey in data:
if survey['id'] not in surveys:
json.dump({'sid': survey['id'], 'svy_ttl': survey['title'], 'svy_link': survey['href']}, f1)
f1.write('\n')
# this line is not needed, it closes thanks to with
# f1.close()
或者,surv如果surveys您希望在data.
import json
with open('old_surveys.json', 'a ') as f1:
f1.seek(0)
surveys = {}
for line in f1:
d = json.loads(line)
surveys[d['sid']] = d
for survey in data:
if survey["id"] not in surveys:
surv = {"sid": survey["id"], "svy_ttl": survey["title"], "svy_link": survey["href"]}
surveys[surv['id']] = surv
json.dump(surv, f1)
f1.write('\n')
如果您真的不需要調查,而只需要識別符號,則效率更高:
import json
with open('old_surveys.json', 'a ') as f1:
f1.seek(0)
surveys = set()
for line in f1:
d = json.loads(line)
surveys.add(d['sid'])
for survey in data:
if survey["id"] not in surveys:
surv = {"sid": survey["id"], "svy_ttl": survey["title"], "svy_link": survey["href"]}
surveys.add(surv['id'])
json.dump(surv, f1)
f1.write('\n')
在這里,字典已被替換為set(),因為您只需要跟蹤識別符號,但在本節之后您將無法訪問其余調查(與以前不同)。
uj5u.com熱心網友回復:
假設你有這樣的檔案
{"sid": 1, "svy_ttl": "foo", "svy_link": "foo.com"}
{"sid": 2, "svy_ttl": "bar", "svy_link": "bar.com"}
{"sid": 3, "svy_ttl": "Alice", "svy_link": "alice.com"}
{"sid": 4, "svy_ttl": "Bob", "svy_link": "bob.com"}
這個代碼片段怎么樣?我不確定這是最佳解決方案
import json
def target_dict_exists(target_dict, filename):
with open(filename, "r") as f:
for line in f:
if json.loads(line) == target_dict:
return True
return False
if __name__ == "__main__":
target = {"sid": 3, "svy_ttl": "Alice", "svy_link": "alice.com"}
print(target_dict_exists(target, "test.txt"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/415354.html
標籤:
上一篇:離子cdk-虛擬滾動
