【问题标题】:Python how can I read file of dictionaries with newline?Python如何用换行符读取字典文件?
【发布时间】:2022-01-19 03:12:29
【问题描述】:

我有一个这样的 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 中。如何逐行阅读?

【问题讨论】:

  • 您是否知道每次写入记录时都会读取整个文件,以查看记录是否已经存在?您想检查是否存在特定字典 - 它需要是整个字典,还是只想检查是否存在共享 sid 的字典?
  • @Grismar 是的,有没有更好的方法来检查重复?
  • @Grismar 整个字典和共享sid 的字典基本上是一回事。
  • 除非您对我不了解的实际数据有所了解,否则在我看来,可能会有一个调查使用相同的sid,但更新后的svy_ttlsvy_link - 在这种情况下,OP 可能想要替换它(或者可能不想 - 谁知道,这就是我要问的原因)

标签: python json file


【解决方案1】:

为了以更有效的方式避免重复,并回答您的问题:

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(),因为您只需要跟踪标识符,但在本节之后您将无法访问其余调查(与以前不同)。

【讨论】:

  • 请注意,就像 OP 的示例一样,这缺少 data 的实际定义 - 我假设 OP 在某个地方有它,并且它适用于他们的示例代码。
【解决方案2】:

假设你有这样的文件

{"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"}

这段代码sn-p怎么样?我不确定这是不是最佳解决方案

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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2014-08-31
    • 1970-01-01
    • 2012-07-06
    • 2015-01-17
    相关资源
    最近更新 更多