简体   繁体   English

如何在 json 文件 python 中读取和写入特定行

[英]how to read and write one specific line in json file python

the json file looks like this: json 文件如下所示:

{
    "Me": {
        "Age": 0,
        "Location": 0,
        "Friends": 0,
        "Family": 0
    },
    "You": {
        "Age": 0,
        "Location": 0,
        "Friends": 0,
        "Family": 0
    }
}

To read ["Me"]["Age"] and assign it to a variable I can use:要读取 ["Me"]["Age"] 并将其分配给我可以使用的变量:

f = open('info.json')
data = json.load(f)
ageinfo = data["Me"]["Age"]

now, if the variable ageinfo updates, I want to send it back to the json file and save it.现在,如果变量ageinfo更新,我想将其发送回 json 文件并保存。 Im not exactly sure how to achieve this, maybe using json.dump?我不确定如何实现这一点,也许使用 json.dump? If anyone could help that would be greatly appreciated.如果有人可以提供帮助,将不胜感激。

yes you can use the json.dump function to do that.是的,您可以使用 json.dump function 来做到这一点。 Imagine you change the content of your dict想象一下,您更改了 dict 的内容

ageinfo = "new_value"

data["Me"]["Age"] = ageinfo

If you want to write it in a file info.json for instance the code would look like this:例如,如果您想将其写入文件 info.json,代码将如下所示:

with open('info.json', 'w') as outfile:
   json.dump(data, outfile)

This will update the file info.json with the content of your dict (or create it if it does not exist)这将使用您的 dict 的内容更新文件 info.json(或者如果它不存在则创建它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中写入文件中的特定行? - How to write to a specific line in file in Python? 如何在 python 中写入和读取 unicode 到 json 文件 - how to write and read unicode to json file in python Python-如何读取文本文件中的特定行? - Python - How to read a specific line in a text file? 如何使用特定的输出格式在python中将矩阵(从一个文件读取)写入另一个csv文件 - How to write a matrix (read from one file) to another csv file in python with a specific output format 我可以用 Python 在一行中读写文件吗? - Can I read and write file in one line with Python? 如何在python中逐行读取和写入.txt文件? - How to read and write the .txt file line by line in python? 如何从特定行读取文件并写入输出? - How to read file from specific line and write the output? 如何在Python的特定字段中读取JSON的多行文件并计算字数 - How Do I Read a Multi-line File of JSON and Count Words in Specific Field in Python 如何在不使用 eval function 的情况下使用 python 从文件的特定行读取 json 数组 - how to read a json array from specific line of a file with python without using eval function Python - 如何在一个 go 的压缩存档中高效地写入/读取 JSON 文件? - Python - How to efficiently write/read a JSON file inside a compressed archive in one go?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM