我有一个类似的json对象文件
dictn
dictn
.
.
.
这就是我如何使这个文件
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()
现在我想检查一个特定的dict是否在文件old_surveys.json
中。我如何逐行阅读?
以更有效的方式避免重复,并回答您的问题:
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()
或者,如果您希望data
中有重复项,您可能仍然希望创建surv
并将其写入文件,以及将其添加到surveys
中。
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()
取代,因为您只需要跟踪标识符,但在本节之后您将无法访问其余的调查(与以前不同(。
假设您有一个类似的文件
{"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"))