读写json文件python
时间: 2023-08-30 20:09:56 浏览: 44
可以使用Python内置的`json`模块来读写JSON文件。下面是一个简单的例子:
```python
import json
# 读取JSON文件
with open('data.json', 'r') as f:
data = json.load(f)
# 输出JSON数据
print(data)
# 修改JSON数据
data['name'] = 'John'
# 写入JSON文件
with open('data.json', 'w') as f:
json.dump(data, f)
```
在这个例子中,我们首先使用`json.load()`函数从`data.json`文件中读取JSON数据,并将其存储在`data`变量中。然后,我们输出`data`变量的内容,并将`name`字段的值修改为`John`。最后,我们使用`json.dump()`函数将修改后的JSON数据写入`data.json`文件中。
相关问题
Python读写json文件
在Python中,可以使用内置的json库来读写JSON文件。下面是一个简单的示例代码:
读取JSON文件:
```python
import json
# 打开JSON文件
with open('data.json', 'r') as f:
# 加载JSON数据
data = json.load(f)
# 使用data变量访问JSON数据
print(data)
```
写入JSON文件:
```python
import json
# 创建一个Python字典
data = {
'name': 'John',
'age': 30,
'city': 'New York'
}
# 打开JSON文件
with open('data.json', 'w') as f:
# 将Python字典转换为JSON格式并写入文件
json.dump(data, f)
```
以上代码中,`data.json` 是要读取或写入的JSON文件的文件路径。你可以根据自己的需求修改文件路径和JSON数据。请确保在读取JSON文件时,文件存在且格式正确。
python 读写json文件
你可以使用Python的内置模块`json`来读写JSON文件。下面是一个示例:
```python
import json
# 读取JSON文件
with open('data.json', 'r') as file:
data = json.load(file)
# 修改数据
data['name'] = 'Alice'
data['age'] = 25
# 写入JSON文件
with open('data.json', 'w') as file:
json.dump(data, file)
```
在这个示例中,我们首先使用`json.load()`函数从文件中加载JSON数据并存储在变量`data`中。然后,我们对`data`进行修改,例如修改"name"和"age"字段的值。最后,我们使用`json.dump()`函数将更新后的数据写回到文件中。
记得将`data.json`替换为你自己的JSON文件路径。