【问题标题】:Add line at file在文件中添加行
【发布时间】:2018-07-05 19:00:01
【问题描述】:

我有一个文件:

"struct_personnal": [
    {
        "id": "1",
        "name": "Mathieu"
    }
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

我想获取一个块的最后一个“}”的行号(struct_hospital、struct_personal 等) 该文件可能包含其他信息。

如果我想在“struct_personnal”块的末尾添加文本,输出是:

"struct_personnal": [
    {
        "id": "1",
        "name": "Mathieu"
    }
   ##############
   #My text here#
   ##############
],
"struct_hospital": [
    {
        "id": "9",
        "geo": "chamb",
        "nb": ""
    },
    {
        "id": "",
        "geo": "jsj",
        "nb": "SMITH"
    },
    {
        "id": "10",
        "geo": "",
        "nb": "12"
    },
    {
        "id": "2",
        "geo": "marqui",
        "nb": "20"
    },
    {
        "id": "4",
        "geo": "oliwo",
        "nb": "1"
    },
    {
        "id": "1",
        "geo": "par",
        "nb": "5"
    }
]

与 struct_hospital 相同

怎么做?我不明白... 谢谢你!

【问题讨论】:

  • 目标是您添加一些自己的代码,以至少显示您为解决这个问题所做的研究工作。
  • 请将该示例输入的所需输出添加到您的问题中。
  • 你的文件看起来像一个json文件,你想实现一个程序吗?如果是,您可以在这种编程语言中使用 json 对象。否则,您可以像计算树一样计算括号。
  • 我已经编辑了我的输出消息
  • 这是一个 json 文件吗?\

标签: sed grep cut


【解决方案1】:

如果它是一个 json 文件,那么我会使用 python。只需加载文件并使用 json.load 函数将 json 内容转换为 python dict。

import json

content = None
with open('path/to/input_file') as f:
    content = json.load(f)

#change the key to struct_hospital if you want to append inside  struct_hospital block
content['struct_personnal'].append({'hi': 'my new text'})

with open('path/to/input_file', 'w') as w:
    json.dump(content, w)

【讨论】:

    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多