我使用Jsonline又名尼德逊,希望使用python编辑单行中的单个键/值,并更新文件中的行。
目前,python库jsonlines和json-线似乎只允许您读取现有条目或编写新条目,而不允许编辑现有条目。
例如,在jsonlines库中,您可以打开文件并在读取器或编写器中包装对象:
import jsonlines
with jsonlines.open('input.jsonl') as reader:
for obj in reader:
...
with jsonlines.open('output.jsonl', mode='w') as writer:
writer.write(...)假设您有以下jsonline文件:
{"name":"Alice","age":24}
{"name":"Bob","age":22}在python中更新字典相当容易。在这种情况下,应该是这样的:
entry = {"name":"Alice","age":24}
entry.update({"age":25})图书馆似乎把这句话作为字典打开了。您可以在jsonline库中调用update方法:
import jsonlines
with open('names.jsonl', 'rb') as f:
for item in json_lines.reader(f):
item.update({'age':25})
print(item['age'])这有两个问题:
names.jsonl保持不变
发布于 2019-04-01 17:12:42
试试下面的代码:
import jsonlines
with jsonlines.open('input.jsonl') as reader, jsonlines.open('output.jsonl', mode='w') as writer:
for obj in reader:
if obj['name'] == 'Alice':
obj['age'] = 25
writer.write(obj)它将将input.jsonl的所有行复制到output.jsonl,并在name字段为Alice时将age字段更改为25。
https://stackoverflow.com/questions/55459942
复制相似问题