python - 如何根据文件中的一个占位符写入字典键和值

标签 python json python-3.x ordereddictionary

我正在尝试验证 json 文件,验证后我想将结果写入新文件。 为此,我在 python 中使用 json 模块。我有一个名为 schema 的字典对象,它包含所有键和值。如果我打印它,我得到的结果如下所示

{'deviceId': 'String', 'userId': 'String', 'regTime': 'Number', 'timestamp': 'String', 'cardiac': 'Number', 'gyro': 'array', 'acc': 'array'}

我想根据占位符 @schema_result 将整个架构结果写入一个文件中。如下所示

deviceId String

userId String

regTime Number

timestamp String

cardiac Number

gyro array

acc array

目前我正在像这样编写这个模式对象

def filing(schema, file_name): #a function that takes schema dictionary and name of file where to write
config = open(file_name, 'w')
for line in open('schema.json', 'r'):
    for key,value in schema.items():
        print(key+" "+value+"\n")
        line = line.replace('@schema_result', str(key+" "+value+"\n"))
    config.write(line)

这只会导致将第一个键和值替换为@schema_result。由于模式对象是字典,我无法添加下一个项目,因为在第一次迭代后,它将用第一个键和值替换@schema_result,下次它找不到@schema_result,因为它已经被替换。

当前结果如下

deviceId String #against @schema_placeholder in first iteration

如何针对文件中的一个占位符写入所有键和值

有两个文件

  • schema.json是包含占位符@schema_result的文件
  • 这个@schema_result被新文件中的输出替换为 file_name变量

最佳答案

您可以使用带有 join 的列表理解来连接整个字典,而不是使用 for 循环从 schema 字典中读取每个项目键值放在一起,然后将其写入文件,

schema = {'deviceId': 'String', 'userId': 'String', 'regTime': 'Number', 'timestamp': 'String', 'cardiac': 'Number', 'gyro': 'array', 'acc': 'array'}


formatted_schema = ["{} {}\n".format(k,v) for k,v in schema.items()]
formatted_schema = ''.join(formatted_schema)

# output,

deviceId String
userId String
regTime Number
timestamp String
cardiac Number
gyro array
acc array

现在您只需将 formatted_schema 写入文件即可将其替换为 @schema_result

关于python - 如何根据文件中的一个占位符写入字典键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029767/

相关文章:

python-3.x - 如何使用命名绑定(bind)与 pandas 数据帧中的 cx_Oracle 中的批量插入 (executemany)

python - 使用python从文本中提取最后一段

python - 断开连接后在python中重新连接到PiCamera流

python - 检查主机 key 是否在python中更改

c# - 解决密码的有效方法

python - 使用给定数据点曲线拟合 Python 中的指数衰减函数

javascript - 如何检查 JavaScript 对象是否为 JSON

asp.net-mvc - 将 application/json 绑定(bind)到 asp.net mvc 中的 POCO 对象,序列化异常

JavaScript 循环以容纳从 Webhook 接收的已过滤对象数组

python - v4l2 文档的示例代码原样(打开为 'rw' )?